utilities.hs 27.4 KB
Newer Older
Henrik Tramberend's avatar
Henrik Tramberend committed
1 2
{-- Author: Henrik Tramberend <henrik@tramberend.de> --} 

Henrik Tramberend's avatar
Henrik Tramberend committed
3
module Utilities
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
  ( calcProjectDirectory
  , spawn
  , terminate
  , threadDelay'
  , wantRepeat
  , defaultContext
  , runShakeInContext
  , watchFiles
  , dropSuffix
  , stopServer
  , startServer
  , runHttpServer
  , writeIndex
  , readMetaDataForDir
  , substituteMetaData
  , markdownToHtmlDeck
  , markdownToHtmlHandout
  , markdownToPdfHandout
  , markdownToHtmlPage
  , markdownToPdfPage
  , writeExampleProject
  , metaValueAsString
  , (<++>)
  , markNeeded
  , replaceSuffixWith
  , writeEmbeddedFiles
  , getRelativeSupportDir
  , pandocMakePdf
  , isCacheableURI
  , adjustLocalUrl
  , cacheRemoteFile
  , cacheRemoteImages
  , makeRelativeTo
  , fixMustacheMarkup
  , fixMustacheMarkupText
  , globA
  , globRelA
41
  , toPandocMeta
42 43
  , DeckerException(..)
  ) where
Henrik Tramberend's avatar
Henrik Tramberend committed
44

Henrik Tramberend's avatar
Henrik Tramberend committed
45
import Common
46 47
import Context
import Control.Arrow
Henrik Tramberend's avatar
Henrik Tramberend committed
48 49
import Control.Concurrent
import Control.Exception
50 51 52 53 54 55
import Control.Monad
import Control.Monad.Loops
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy as LB
import qualified Data.ByteString.Lazy.Char8 as L8
import Data.Digest.Pure.MD5
56
import Data.Dynamic
57 58 59
import qualified Data.HashMap.Lazy as HashMap
import qualified Data.HashMap.Strict as H
import Data.IORef
60
import Data.List
Henrik Tramberend's avatar
Henrik Tramberend committed
61
import Data.List.Extra
62
import qualified Data.Map.Lazy as Map
Henrik Tramberend's avatar
Henrik Tramberend committed
63
import Data.Maybe
64
import qualified Data.Set as Set
Henrik Tramberend's avatar
Henrik Tramberend committed
65
import qualified Data.Text as T
66
import qualified Data.Text.Encoding as E
67 68 69 70 71 72 73 74 75 76 77
import qualified Data.Vector as Vec
import qualified Data.Yaml as Y
import Debug.Trace
import Development.Shake
import Development.Shake.FilePath as SFP
import Embed
import Filter
import Network.HTTP.Conduit
import Network.HTTP.Simple
import Network.HTTP.Types.Status
import Network.URI
Henrik Tramberend's avatar
Henrik Tramberend committed
78
import Project
79
import System.Directory as Dir
80
import System.FilePath as SF
Henrik Tramberend's avatar
Henrik Tramberend committed
81
import System.FilePath.Glob
Henrik Tramberend's avatar
Henrik Tramberend committed
82
import System.IO as S
83 84 85
import System.Process
import System.Process.Internals
import Text.CSL.Pandoc
Henrik Tramberend's avatar
Henrik Tramberend committed
86 87 88 89
import qualified Text.Mustache as M
import qualified Text.Mustache.Types as MT
import Text.Pandoc
import Text.Pandoc.PDF
90
import Text.Pandoc.Walk
91
import Watch
92

93 94
-- Find the project directory and change current directory to there. 
-- The project directory is the first upwards directory that contains a .git directory entry.
95
calcProjectDirectory :: IO FilePath
96 97 98 99 100 101 102 103 104 105 106 107 108
calcProjectDirectory = do
  cwd <- getCurrentDirectory
  searchGitRoot cwd
  where
    searchGitRoot :: FilePath -> IO FilePath
    searchGitRoot path =
      if isDrive path
        then makeAbsolute "."
        else do
          hasGit <- Dir.doesDirectoryExist (path </> ".git")
          if hasGit
            then makeAbsolute path
            else searchGitRoot $ takeDirectory path
Henrik Tramberend's avatar
Henrik Tramberend committed
109

110 111 112
-- | Globs for files under the project dir in the Action monad. 
-- Returns absolute pathes. 
globA :: FilePattern -> Action [FilePath]
113
globA pat = do
114 115
  dirs <- getProjectDirs
  liftIO $ globDir1 (compile pat) (project dirs)
116 117 118 119

-- | Globs for files under the project dir in the Action monad. 
-- Returns pathes relative to the project directory. 
globRelA :: FilePattern -> Action [FilePath]
120
globRelA pat = do
121
  dirs <- getProjectDirs
122
  files <- globA pat
123
  return $ map (makeRelative (project dirs)) files
124

Henrik Tramberend's avatar
Henrik Tramberend committed
125 126 127 128
-- Utility functions for shake based apps
spawn :: String -> Action ProcessHandle
spawn = liftIO . spawnCommand

129
-- Runs liveroladx on the given directory, if it is not already running. If
Henrik Tramberend's avatar
Henrik Tramberend committed
130
-- open is True a browser window is opended.
131 132 133 134 135 136 137 138 139 140
runHttpServer dir open = do
  process <- getServerHandle
  case process of
    Just handle -> return ()
    Nothing -> do
      putNormal "# livereloadx (on http://localhost:8888, see server.log)"
      handle <-
        spawn $ "livereloadx -s -p 8888 -d 500 " ++ dir ++ " 2>&1 > server.log"
      setServerHandle $ Just handle
      threadDelay' 200000
141
      when open $ cmd ("open http://localhost:8888/" :: String) :: Action ()
Henrik Tramberend's avatar
Henrik Tramberend committed
142

143
startServer id command =
144 145 146
  liftIO $ do
    processHandle <- spawnCommand command
    withProcessHandle processHandle handleResult
147 148 149 150 151 152 153 154
  where
    handleResult ph =
      case ph of
        ClosedHandle e ->
          print $ "Error starting server " ++ id ++ ": " ++ show e
        OpenHandle p -> do
          print $ "Server " ++ id ++ " running (" ++ show p ++ ")"
          writeFile (id ++ ".pid") (show p)
Henrik Tramberend's avatar
Henrik Tramberend committed
155

156
stopServer id =
157 158 159 160 161 162 163 164
  liftIO $ do
    let pidFile = id ++ ".pid"
    result <- try $ readFile pidFile
    case result of
      Left (SomeException e) -> print $ "Unable to read file " ++ pidFile
      Right pid -> do
        exitCode <- system ("kill -9 " ++ pid)
        removeFile pidFile
Henrik Tramberend's avatar
Henrik Tramberend committed
165 166 167 168 169 170 171 172 173 174

terminate :: ProcessHandle -> Action ()
terminate = liftIO . terminateProcess

threadDelay' :: Int -> Action ()
threadDelay' = liftIO . threadDelay

wantRepeat :: IORef Bool -> Action ()
wantRepeat justOnce = liftIO $ writeIORef justOnce False

175 176
-- The context of program invocation consists of a list of
-- files to watch and a possibly running local http server.
Henrik Tramberend's avatar
Henrik Tramberend committed
177 178 179 180 181 182
data Context =
  Context [FilePath]
          (Maybe ProcessHandle)

defaultContext = Context [] Nothing

183
runShakeInContext :: ActionContext -> ShakeOptions -> Rules () -> IO ()
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
runShakeInContext context options rules = do
  opts <- setActionContext context options
  catch
    (untilM_ (tryRunShake opts) nothingToWatch)
    (\(SomeException e) -> putStrLn $ "Terminated: " ++ show e)
  cleanup
  where
    tryRunShake opts =
      catch (shakeArgs opts rules) (\(SomeException e) -> return ())
    cleanup = do
      process <- readIORef $ ctxServerHandle context
      case process of
        Just handle -> terminateProcess handle
        Nothing -> return ()
    nothingToWatch = do
      files <- readIORef $ ctxFilesToWatch context
      if null files
        then return True
        else do
203
          waitForTwitchPassive files
204
          return False
Henrik Tramberend's avatar
Henrik Tramberend committed
205

206
watchFiles = setFilesToWatch
Henrik Tramberend's avatar
Henrik Tramberend committed
207 208

-- | Monadic version of list concatenation.
Henrik Tramberend's avatar
Henrik Tramberend committed
209
(<++>) :: Monad m => m [a] -> m [a] -> m [a]
210
(<++>) = liftM2 (++)
Henrik Tramberend's avatar
Henrik Tramberend committed
211 212 213

-- | Mark files as need and return them
markNeeded :: [FilePath] -> Action [FilePath]
214 215 216
markNeeded files = do
  need files
  return files
Henrik Tramberend's avatar
Henrik Tramberend committed
217 218 219 220 221

-- | Removes the last suffix from a filename
dropSuffix s t = fromMaybe t (stripSuffix s t)

-- | Monadic version of suffix replacement for easy binding.
222
replaceSuffixWith :: String -> String -> [FilePath] -> Action [FilePath]
223
replaceSuffixWith suffix with pathes =
Henrik Tramberend's avatar
Henrik Tramberend committed
224 225
  return [dropSuffix suffix d ++ with | d <- pathes]

226
-- | Monadic version of suffix replacement for easy binding.
Henrik Tramberend's avatar
Henrik Tramberend committed
227 228
calcTargetPath ::
     FilePath -> String -> String -> [FilePath] -> Action [FilePath]
229 230 231 232
calcTargetPath projectDir suffix with pathes =
  return [projectDir </> dropSuffix suffix d ++ with | d <- pathes]

-- | Generates an index.md file with links to all generated files of interest.
233 234 235 236
writeIndex out baseUrl decks handouts pages = do
  let decksLinks = map (makeRelative baseUrl) decks
  let handoutsLinks = map (makeRelative baseUrl) handouts
  let pagesLinks = map (makeRelative baseUrl) pages
237
  dirs <- getProjectDirs
238 239 240 241 242
  liftIO $
    writeFile out $
    unlines
      [ "---"
      , "title: Generated Index"
243
      , "subtitle: " ++ (project dirs)
244 245 246 247 248 249 250 251 252 253 254
      , "---"
      , "# Slide decks"
      , unlines $ map makeLink $ sort decksLinks
      , "# Handouts"
      , unlines $ map makeLink $ sort handoutsLinks
      , "# Supporting Documents"
      , unlines $ map makeLink $ sort pagesLinks
      ]
  where
    makeLink path = "-    [" ++ takeFileName path ++ "](" ++ path ++ ")"

255 256 257 258 259 260
joinMeta :: Y.Value -> Y.Value -> Y.Value
joinMeta (Y.Object old) (Y.Object new) = Y.Object (H.union new old)
joinMeta (Y.Object old) _ = Y.Object old
joinMeta _ (Y.Object new) = Y.Object new
joinMeta _ _ = throw $ YamlException "Can only join YAML objects."

261
readMetaDataForDir :: FilePath -> Action Y.Value
262 263 264
readMetaDataForDir dir = walkUpTo dir
  where
    walkUpTo dir = do
265 266
      dirs <- getProjectDirs
      if equalFilePath (project dirs) dir
267 268 269 270 271
        then collectMeta dir
        else do
          fromAbove <- walkUpTo (takeDirectory dir)
          fromHere <- collectMeta dir
          return $ joinMeta fromHere fromAbove
272 273
    --
    collectMeta dir = do
274 275 276 277
      files <- liftIO $ globDir1 (compile "*-meta.yaml") dir
      need files
      meta <- mapM decodeYaml files
      return $ foldl joinMeta (Y.object []) meta
278 279
    --
    decodeYaml yamlFile = do
280 281 282 283 284 285 286
      result <- liftIO $ Y.decodeFileEither yamlFile
      case result of
        Right object@(Y.Object _) -> return object
        Right _ ->
          throw $
          YamlException $ "Top-level meta value must be an object: " ++ dir
        Left exception -> throw exception
Henrik Tramberend's avatar
Henrik Tramberend committed
287

288 289 290 291 292 293
-- | Fixes pandoc escaped # markup in mustache template {{}} markup.
fixMustacheMarkup :: B.ByteString -> T.Text
fixMustacheMarkup content = fixMustacheMarkupText $ E.decodeUtf8 content

-- | Fixes pandoc escaped # markup in mustache template {{}} markup.
fixMustacheMarkupText :: T.Text -> T.Text
294 295 296 297 298 299
fixMustacheMarkupText content =
  T.replace
    (T.pack "{{\\#")
    (T.pack "{{#")
    (T.replace (T.pack "{{\\^") (T.pack "{{^") content)

300 301 302 303 304 305 306 307
substituteMetaData :: T.Text -> MT.Value -> T.Text
substituteMetaData text metaData = do
  let fixed = fixMustacheMarkupText text
  let result = M.compileTemplate "internal" fixed
  case result of
    Right template -> M.substituteValue template metaData
    Left err -> throw $ MustacheException (show err)

308
getRelativeSupportDir :: FilePath -> Action FilePath
309
getRelativeSupportDir from = do
310
  dirs <- getProjectDirs
311
  return $
312 313
    invertPath (makeRelative (public dirs) (takeDirectory from)) </>
    makeRelative (public dirs) (support dirs)
Henrik Tramberend's avatar
Henrik Tramberend committed
314 315

invertPath :: FilePath -> FilePath
316
invertPath fp = joinPath $ map (const "..") $ filter ("." /=) $ splitPath fp
Henrik Tramberend's avatar
Henrik Tramberend committed
317 318

-- | Write a markdown file to a HTML file using the page template.
319 320 321 322 323
markdownToHtmlDeck :: FilePath -> FilePath -> Action ()
markdownToHtmlDeck markdownFile out = do
  supportDir <- getRelativeSupportDir out
  let options =
        pandocWriterOpts
324 325
        { writerTemplate = Just deckTemplate
        -- , writerStandalone = True
326
        , writerHighlight = True
327
        -- , writerHighlightStyle = pygments
328
        , writerHTMLMathMethod =
329 330
            MathJax
              (supportDir </> "MathJax-2.7/MathJax.js?config=TeX-AMS_HTML")
331 332 333 334
        -- ,writerHTMLMathMethod =
        --    KaTeX (supportDir </> "katex-0.6.0/katex.min.js")
        --          (supportDir </> "katex-0.6.0/katex.min.css")
        , writerVariables =
335 336 337
            [ ("revealjs-url", supportDir </> "reveal.js")
            , ("decker-support-dir", supportDir)
            ]
338 339 340 341 342
        , writerCiteMethod = Citeproc
        }
  pandoc <- readAndPreprocessMarkdown markdownFile
  processed <- processPandocDeck "revealjs" pandoc
  writePandocString "revealjs" options out processed
343

Henrik Tramberend's avatar
Henrik Tramberend committed
344 345 346 347 348 349 350 351 352 353
-- | Selects a matching pandoc string writer for the format string, or throws an
-- exception.
getPandocWriter :: String -> StringWriter
getPandocWriter format =
  case getWriter format of
    Right (PureStringWriter w) -> w
    Left e -> throw $ PandocException e
    _ -> throw $ PandocException $ "No writer for format: " ++ format

-- | Reads a markdownfile, expands the included files, and substitutes mustache
354 355
-- template variables and calls need.
readAndPreprocessMarkdown :: FilePath -> Action Pandoc
356
readAndPreprocessMarkdown markdownFile = do
357
  dirs <- getProjectDirs
358
  let baseDir = takeDirectory markdownFile
Henrik Tramberend's avatar
Henrik Tramberend committed
359 360
  readMetaMarkdown markdownFile >>= processIncludes (project dirs) baseDir >>=
    locateTemplates (project dirs) baseDir
361 362
  -- Disable automatic caching of remomte images for a while
  -- >>= populateCache
Henrik Tramberend's avatar
Henrik Tramberend committed
363 364

populateCache :: Pandoc -> Action Pandoc
365
populateCache pandoc = do
366 367
  dirs <- getProjectDirs
  liftIO $ walkM (cacheRemoteImages (cache dirs)) pandoc
Henrik Tramberend's avatar
Henrik Tramberend committed
368

Henrik Tramberend's avatar
Henrik Tramberend committed
369
-- | Write a markdown file to a HTML file using the page template.
370 371 372 373 374 375
markdownToHtmlPage :: FilePath -> FilePath -> Action ()
markdownToHtmlPage markdownFile out = do
  supportDir <- getRelativeSupportDir out
  let options =
        pandocWriterOpts
        { writerHtml5 = True
376 377
        -- , writerStandalone = True
        , writerTemplate = Just pageTemplate
378
        , writerHighlight = True
379
        -- , writerHighlightStyle = pygments
380
        , writerHTMLMathMethod =
381 382
            MathJax
              (supportDir </> "MathJax-2.7/MathJax.js?config=TeX-AMS_HTML")
383 384 385 386 387 388 389 390 391
        -- ,writerHTMLMathMethod =
        --    KaTeX (supportDir </> "katex-0.6.0/katex.min.js")
        --          (supportDir </> "katex-0.6.0/katex.min.css")
        , writerVariables = [("decker-support-dir", supportDir)]
        , writerCiteMethod = Citeproc
        }
  pandoc <- readAndPreprocessMarkdown markdownFile
  processed <- processPandocPage "html5" pandoc
  writePandocString "html5" options out processed
Henrik Tramberend's avatar
Henrik Tramberend committed
392 393

-- | Write a markdown file to a PDF file using the handout template.
394 395 396 397
markdownToPdfPage :: FilePath -> FilePath -> Action ()
markdownToPdfPage markdownFile out = do
  let options =
        pandocWriterOpts
398 399
        { writerTemplate = Just pageLatexTemplate
        -- , writerStandalone = True
400
        , writerHighlight = True
401
        -- , writerHighlightStyle = pygments
402 403 404 405 406 407 408 409 410 411 412 413
        , writerCiteMethod = Citeproc
        }
  pandoc <- readAndPreprocessMarkdown markdownFile
  processed <- processPandocPage "latex" pandoc
  putNormal $ "# pandoc (for " ++ out ++ ")"
  pandocMakePdf options processed out

pandocMakePdf options processed out = do
  result <- liftIO $ makePDF "pdflatex" writeLaTeX options processed
  case result of
    Left err -> throw $ PandocException (show err)
    Right pdf -> liftIO $ LB.writeFile out pdf
Henrik Tramberend's avatar
Henrik Tramberend committed
414 415

-- | Write a markdown file to a HTML file using the handout template.
416 417 418 419 420 421 422 423
markdownToHtmlHandout :: FilePath -> FilePath -> Action ()
markdownToHtmlHandout markdownFile out = do
  pandoc <- readAndPreprocessMarkdown markdownFile
  processed <- processPandocHandout "html" pandoc
  supportDir <- getRelativeSupportDir out
  let options =
        pandocWriterOpts
        { writerHtml5 = True
424 425
        -- , writerStandalone = True
        , writerTemplate = Just handoutTemplate
426
        , writerHighlight = True
427
        -- , writerHighlightStyle = pygments
428
        , writerHTMLMathMethod =
429 430
            MathJax
              (supportDir </> "MathJax-2.7/MathJax.js?config=TeX-AMS_HTML")
431 432 433 434 435 436 437
        -- ,writerHTMLMathMethod =
        --    KaTeX (supportDir </> "katex-0.6.0/katex.min.js")
        --          (supportDir </> "katex-0.6.0/katex.min.css")
        , writerVariables = [("decker-support-dir", supportDir)]
        , writerCiteMethod = Citeproc
        }
  writePandocString "html5" options out processed
Henrik Tramberend's avatar
Henrik Tramberend committed
438 439

-- | Write a markdown file to a PDF file using the handout template.
440
markdownToPdfHandout :: FilePath -> FilePath -> Action ()
441
markdownToPdfHandout markdownFile out = do
442 443 444 445
  pandoc <- readAndPreprocessMarkdown markdownFile
  processed <- processPandocHandout "latex" pandoc
  let options =
        pandocWriterOpts
446 447
        { writerTemplate = Just handoutLatexTemplate
        -- , writerStandalone = True
448
        , writerHighlight = True
449
        -- , writerHighlightStyle = pygments
450 451 452 453
        , writerCiteMethod = Citeproc
        }
  putNormal $ "# pandoc (for " ++ out ++ ")"
  pandocMakePdf options processed out
454

455
-- | Reads a markdown file and returns a pandoc document. 
456
readMetaMarkdown :: FilePath -> Action Pandoc
457 458
readMetaMarkdown markdownFile = do
  need [markdownFile]
459
  -- read external meta data for this directory
Henrik Tramberend's avatar
Henrik Tramberend committed
460
  externalMeta <- readMetaDataForDir (takeDirectory markdownFile)
461
  -- extract embedded meta data from the document
Henrik Tramberend's avatar
Henrik Tramberend committed
462 463 464
  markdown <- liftIO $ S.readFile markdownFile
  let Pandoc meta _ = readMarkdownOrThrow pandocReaderOpts markdown
  let documentMeta = MetaMap $ unMeta meta
465
  -- combine the meta data with preference on the embedded data
Henrik Tramberend's avatar
Henrik Tramberend committed
466 467 468 469 470 471 472 473 474
  let combinedMeta = mergePandocMeta documentMeta (toPandocMeta externalMeta)
  let mustacheMeta = toMustacheMeta combinedMeta
   -- use mustache to substitute
  let substituted = substituteMetaData (T.pack markdown) mustacheMeta
  -- read markdown with substitutions again
  let Pandoc _ blocks =
        readMarkdownOrThrow pandocReaderOpts $ T.unpack substituted
  let (MetaMap m) = combinedMeta
  let pandoc = Pandoc (Meta m) blocks
475
  -- adjust image urls
476
  dirs <- getProjectDirs
Henrik Tramberend's avatar
Henrik Tramberend committed
477
  -- TODO: This has to go
478
  return $ walk (adjustImageUrls (project dirs) (takeDirectory markdownFile)) pandoc
Henrik Tramberend's avatar
Henrik Tramberend committed
479 480
  -- TODO: Make this work further down
  -- provisionResources dirs (takeDirectory markdownFile) pandoc
Henrik Tramberend's avatar
Henrik Tramberend committed
481 482 483 484 485
  where
    readMarkdownOrThrow opts string =
      case readMarkdown opts string of
        Right pandoc -> pandoc
        Left err -> throw $ PandocException (show err)
486

487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
-- | Converts pandoc meta data to mustache meta data. Inlines and blocks are rendered to 
-- markdown strings with default options.
toMustacheMeta :: MetaValue -> MT.Value
toMustacheMeta (MetaMap mmap) =
  MT.Object $ H.fromList $ map (T.pack *** toMustacheMeta) $ Map.toList mmap
toMustacheMeta (MetaList a) = MT.Array $ Vec.fromList $ map toMustacheMeta a
toMustacheMeta (MetaBool bool) = MT.Bool bool
toMustacheMeta (MetaString string) = MT.String $ T.pack string
toMustacheMeta (MetaInlines inlines) =
  MT.String $
  T.pack $ writeMarkdown def (Pandoc (Meta Map.empty) [(Plain inlines)])
toMustacheMeta (MetaBlocks blocks) =
  MT.String $ T.pack $ writeMarkdown def (Pandoc (Meta Map.empty) blocks)

mergePandocMeta :: MetaValue -> MetaValue -> MetaValue
mergePandocMeta (MetaMap left) (MetaMap right) = MetaMap $ Map.union left right
mergePandocMeta left _ = left

-- | Converts YAML meta data to pandoc meta data.
toPandocMeta :: Y.Value -> MetaValue
toPandocMeta (Y.Object m) =
  MetaMap $ Map.fromList $ map (T.unpack *** toPandocMeta) $ H.toList m
toPandocMeta (Y.Array vector) = MetaList $ map toPandocMeta $ Vec.toList vector
toPandocMeta (Y.String text) = MetaString $ T.unpack text
toPandocMeta (Y.Number scientific) = MetaString $ show scientific
toPandocMeta (Y.Bool bool) = MetaBool bool
toPandocMeta (Y.Null) = MetaList []

515 516 517 518 519 520 521
-- Remove automatic identifier creation for headers. It does not work well with
-- the current include mechanism, if slides have duplicate titles in separate
-- include files.
deckerPandocExtensions :: Set.Set Extension
deckerPandocExtensions = Set.delete Ext_auto_identifiers pandocExtensions

pandocReaderOpts :: ReaderOptions
522
pandocReaderOpts = def {readerExtensions = deckerPandocExtensions}
523 524

pandocWriterOpts :: WriterOptions
525
pandocWriterOpts = def {writerExtensions = deckerPandocExtensions}
526

527 528 529 530 531 532 533 534 535
isLocalURI :: String -> Bool
isLocalURI url = isNothing $ parseURI url

isRemoteURI :: String -> Bool
isRemoteURI = not . isLocalURI

isCacheableURI :: String -> Bool
isCacheableURI url =
  case parseURI url of
536
    Just uri -> uriScheme uri `elem` ["http:", "https:"]
537 538 539 540 541 542 543
    Nothing -> False

-- | Walks over all images in a Pandoc document and transforms image URLs like
-- this: 1. Remote URLs are not transformed. 2. Absolute URLs are intepreted
-- relative to the project root directory. 3. Relative URLs are intepreted
-- relative to the containing document.
adjustImageUrls :: FilePath -> FilePath -> Pandoc -> Pandoc
544
adjustImageUrls projectDir baseDir = walk adjustBlock . walk adjustInline
545
  where
546 547
    adjustInline (Image attr inlines (url, title)) =
      Image attr inlines (adjustLocalUrl projectDir baseDir url, title)
548 549
    adjustInline other = other
    adjustBlock (Header 1 attr inlines) =
550
      Header 1 (adjustBgImageUrl attr) inlines
551
    adjustBlock other = other
552 553 554 555 556
    adjustBgImageUrl (i, cs, kvs) =
      ( i
      , cs
      , map
          (\(k, v) ->
557 558 559
             if k == "data-background-image" || k == "data-background-video"
               then (k, adjustLocalUrl projectDir baseDir v)
               else (k, v))
560
          kvs)
561 562 563 564

adjustLocalUrl :: FilePath -> FilePath -> FilePath -> FilePath
adjustLocalUrl root base url
  | isLocalURI url =
565 566 567
    if isAbsolute url
      then root </> makeRelative "/" url
      else base </> url
568 569
adjustLocalUrl _ _ url = url

Henrik Tramberend's avatar
Henrik Tramberend committed
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
locateTemplates :: FilePath -> FilePath -> Pandoc -> Action Pandoc
locateTemplates root base (Pandoc meta blocks) = do
  return (Pandoc meta blocks)

-- TODO: Make this compile, than work
-- provisionResources :: ProjectDirs -> FilePath -> Pandoc -> Action Pandoc
-- provisionResources dirs base pandoc@(Pandoc meta blocks) = do
--   let provisioning = provisioningFromMeta meta
--   liftIO $ walkM (provision provisioning) pandoc
--   where
--     provision (Image attr inlines target) provisioning =
--       Image (provision_ attr provisioning) inlines target
--     provision anything _ = anything
--     provision_ (ident, klass, kvs) provisioning =
--       map (\(k, v) -> (k, provisionResource provisioning dirs base v))

Henrik Tramberend's avatar
Henrik Tramberend committed
586
-- Transitively splices all include files into the pandoc document.
587
processIncludes :: FilePath -> FilePath -> Pandoc -> Action Pandoc
588
processIncludes rootDir baseDir (Pandoc meta blocks) = do
589 590
  included <- processBlocks baseDir blocks
  return $ Pandoc meta included
591 592 593
  where
    processBlocks :: FilePath -> [Block] -> Action [Block]
    processBlocks base blcks = do
594 595
      spliced <- foldM (include base) [] blcks
      return $ concat $ reverse spliced
596
    include :: FilePath -> [[Block]] -> Block -> Action [[Block]]
597
    include base result (Para [Link _ [Str "#include"] (url, _)]) = do
Henrik Tramberend's avatar
Henrik Tramberend committed
598
      filePath <- liftIO $ findResource rootDir base url
599 600 601
      Pandoc _ b <- readMetaMarkdown filePath
      included <- processBlocks (takeDirectory filePath) b
      return $ included : result
602
    include _ result block = return $ [block] : result
603

Henrik Tramberend's avatar
Henrik Tramberend committed
604
cacheRemoteImages :: FilePath -> Pandoc -> IO Pandoc
605
cacheRemoteImages cacheDir = walkM cacheRemoteImage
606
  where
607 608 609
    cacheRemoteImage (Image attr inlines (url, title)) = do
      cachedFile <- cacheRemoteFile cacheDir url
      return (Image attr inlines (cachedFile, title))
610
    cacheRemoteImage img = return img
Henrik Tramberend's avatar
Henrik Tramberend committed
611 612 613

cacheRemoteFile :: FilePath -> String -> IO FilePath
cacheRemoteFile cacheDir url
614
  | isCacheableURI url = do
615 616 617 618 619 620 621 622 623 624 625 626
    let cacheFile = cacheDir </> hashURI url
    exists <- Dir.doesFileExist cacheFile
    if exists
      then return cacheFile
      else catch
             (do content <- downloadUrl url
                 createDirectoryIfMissing True cacheDir
                 LB.writeFile cacheFile content
                 return cacheFile)
             (\e -> do
                putStrLn $ "Warning: " ++ show (e :: SomeException)
                return url)
Henrik Tramberend's avatar
Henrik Tramberend committed
627 628 629 630
cacheRemoteFile _ url = return url

clearCachedFile :: FilePath -> String -> IO ()
clearCachedFile cacheDir url
631
  | isCacheableURI url = do
632 633 634
    let cacheFile = cacheDir </> hashURI url
    exists <- Dir.doesFileExist cacheFile
    when exists $ removeFile cacheFile
Henrik Tramberend's avatar
Henrik Tramberend committed
635 636 637
clearCachedFile _ _ = return ()

downloadUrl :: String -> IO LB.ByteString
638
downloadUrl url = do
639 640 641 642 643 644 645 646 647 648 649 650
  request <- parseRequest url
  result <- httpLBS request
  let status = getResponseStatus result
  if status == ok200
    then return $ getResponseBody result
    else throw $
         HttpException $
         "Cannot download " ++
         url ++
         " (" ++
         show (statusCode status) ++
         " " ++ B.unpack (statusMessage status) ++ ")"
Henrik Tramberend's avatar
Henrik Tramberend committed
651 652

hashURI :: String -> String
653
hashURI uri = show (md5 $ L8.pack uri) SF.<.> SF.takeExtension uri
Henrik Tramberend's avatar
Henrik Tramberend committed
654

655
processPandocPage :: String -> Pandoc -> Action Pandoc
656
processPandocPage format pandoc = do
657
  let f = Just (Format format)
658
  dirs <- getProjectDirs
659
  processed <-
660 661
    liftIO $ processCites' pandoc >>= walkM (useCachedImages (cache dirs))
  --  processed <- liftIO $ walkM (useCachedImages (cache dirs)) pandoc
662 663 664 665 666
  return $ expandMacros f processed

processPandocDeck :: String -> Pandoc -> Action Pandoc
processPandocDeck format pandoc = do
  let f = Just (Format format)
667
  dirs <- getProjectDirs
668
  processed <-
669 670
    liftIO $ processCites' pandoc >>= walkM (useCachedImages (cache dirs))
  -- processed <- liftIO $ walkM (useCachedImages cacheD(cache dirs)ir) pandoc
671 672 673 674 675
  return $ (makeSlides f . expandMacros f) processed

processPandocHandout :: String -> Pandoc -> Action Pandoc
processPandocHandout format pandoc = do
  let f = Just (Format format)
676
  dirs <- getProjectDirs
677
  processed <-
678 679
    liftIO $ processCites' pandoc >>= walkM (useCachedImages (cache dirs))
  -- processed <- liftIO $ walkM (useCachedImages (cache dirs)) pandoc
680
  return $ (expandMacros f . filterNotes f) processed
Henrik Tramberend's avatar
Henrik Tramberend committed
681 682 683

type StringWriter = WriterOptions -> Pandoc -> String

684
writePandocString :: String -> WriterOptions -> FilePath -> Pandoc -> Action ()
685 686 687 688 689
writePandocString format options out pandoc = do
  let writer = getPandocWriter format
  final <- copyImages (takeDirectory out) pandoc
  writeFile' out (writer options final)
  putNormal $ "# pandoc for (" ++ out ++ ")"
Henrik Tramberend's avatar
Henrik Tramberend committed
690

Henrik Tramberend's avatar
Henrik Tramberend committed
691
copyImages :: FilePath -> Pandoc -> Action Pandoc
692
copyImages baseDir pandoc = do
693 694 695
  dirs <- getProjectDirs
  walkM (copyAndLinkInline (project dirs) (public dirs)) pandoc >>=
    walkM (copyAndLinkBlock (project dirs) (public dirs))
696
  where
697 698 699
    copyAndLinkInline project public (Image attr inlines (url, title)) = do
      relUrl <- copyAndLinkFile project public baseDir url
      return (Image attr inlines (relUrl, title))
700 701
    copyAndLinkInline _ _ inline = return inline
    copyAndLinkBlock project public (Header 1 attr inlines) = do
702 703
      relAttr <- copyBgImageUrl project public attr
      return (Header 1 relAttr inlines)
704
    copyAndLinkBlock _ _ block = return block
705 706 707 708
    copyBgImageUrl project public (i, cs, kvs) = do
      relKvs <-
        mapM
          (\(k, v) ->
709 710 711 712 713
             if k == "data-background-image"
               then do
                 relUrl <- copyAndLinkFile project public baseDir v
                 return (k, relUrl)
               else return (k, v))
714 715 716
          kvs
      return (i, cs, relKvs)

Henrik Tramberend's avatar
Henrik Tramberend committed
717 718
copyAndLinkFile ::
     FilePath -> FilePath -> FilePath -> FilePath -> Action FilePath
719
copyAndLinkFile project public base url = do
720 721 722 723 724 725 726
  let rel = makeRelative project url
  if rel == url
    then return url
    else do
      let pub = public </> rel
      liftIO $ createDirectoryIfMissing True (takeDirectory pub)
      copyFileChanged url pub
Henrik Tramberend's avatar
Henrik Tramberend committed
727
      return $ makeRelativeTo base pub
728 729 730

-- | Express the second path argument as relative to the first. 
-- Both arguments are expected to be absolute pathes. 
731 732 733 734 735 736 737 738 739 740
-- makeRelativeTo :: FilePath -> FilePath -> FilePath
-- makeRelativeTo dir file =
--   let (d, f) = removeCommonPrefix (splitDirectories dir) (splitDirectories file)
--   in normalise $ invertPath (joinPath d) </> joinPath f
-- removeCommonPrefix :: [FilePath] -> [FilePath] -> ([FilePath], [FilePath])
-- removeCommonPrefix al@(a:as) bl@(b:bs)
--  | a == b = removeCommonPrefix as bs
--  | otherwise = (al, bl)
-- removeCommonPrefix a [] = (a, [])
-- removeCommonPrefix [] b = ([], b)
Henrik Tramberend's avatar
Henrik Tramberend committed
741
writeExampleProject :: Action ()
742
writeExampleProject = mapM_ writeOne deckerExampleDir
743
  where
744 745
    writeOne (path, contents) = do
      exists <- Development.Shake.doesFileExist path
746 747 748 749
      unless exists $ do
        liftIO $ createDirectoryIfMissing True (takeDirectory path)
        liftIO $ B.writeFile path contents
        putNormal $ "# create (for " ++ path ++ ")"
Henrik Tramberend's avatar
Henrik Tramberend committed
750

751
writeEmbeddedFiles :: [(FilePath, B.ByteString)] -> FilePath -> Action ()
752
writeEmbeddedFiles files dir = do
753 754
  let absolute = map (\(path, contents) -> (dir </> path, contents)) files
  mapM_ write absolute
755
  where
756 757 758 759
    write (path, contents) = do
      liftIO $ Dir.createDirectoryIfMissing True (takeDirectory path)
      exists <- liftIO $ Dir.doesFileExist path
      unless exists $ liftIO $ B.writeFile path contents
760

Henrik Tramberend's avatar
Henrik Tramberend committed
761
lookupValue :: String -> Y.Value -> Maybe Y.Value
762
lookupValue key (Y.Object hashTable) = HashMap.lookup (T.pack key) hashTable
Henrik Tramberend's avatar
Henrik Tramberend committed
763 764
lookupValue key _ = Nothing

765
metaValueAsString :: String -> Y.Value -> Maybe String
Henrik Tramberend's avatar
Henrik Tramberend committed
766
metaValueAsString key meta =
767 768 769
  case splitOn "." key of
    [] -> Nothing
    k:ks -> lookup' ks (lookupValue k meta)
770 771
  where
    lookup' :: [String] -> Maybe Y.Value -> Maybe String
772
    lookup' [] (Just (Y.String text)) = Just (T.unpack text)
773 774 775 776
    lookup' [] (Just (Y.Number n)) = Just (show n)
    lookup' [] (Just (Y.Bool b)) = Just (show b)
    lookup' (k:ks) (Just obj@(Y.Object _)) = lookup' ks (lookupValue k obj)
    lookup' _ _ = Nothing