summaryrefslogtreecommitdiff
path: root/hs/src/Handlingar/HtmlOutput.hs
blob: 320df19801744f495a67b7658847838892e102d6 (plain)
1
2
3
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
{-# LANGUAGE OverloadedStrings
           , ImportQualifiedPost
           #-}

module Handlingar.HtmlOutput
( handleHtml
) where

import Control.Monad.State.Lazy
import Data.Default (def)
import Text.Pandoc.Extract (AppendixItem, getHeadingData)
import Text.Pandoc (readVimwiki, PandocIO)
import Text.Pandoc.Definition (Meta(..))
import Text.Pandoc.Builder
import Data.Text (Text, unpack, pack)
import Text.Pandoc.Writers.HTML (writeHtml5String)
import Handlingar.Common (handleBilaga, HandlingarOps(..), buildPrimary)
import System.FilePath ((</>), takeExtension)
import Data.Text.IO (writeFile)
import Data.Text qualified as T
import System.Directory (copyFile)
import System.Posix.Directory (changeWorkingDirectory, getWorkingDirectory)
import Control.Exception (catch)
import Data.Map.Strict qualified as Map
import Text.DocTemplates (compileTemplateFile)
import Text.Pandoc.Templates ( Template(..), getTemplate, renderTemplate, WithDefaultPartials(..))
import Text.DocTemplates ()
import Text.Pandoc (readVimwiki, WriterOptions(writerTemplate, writerListings, writerVariables), PandocIO)
import System.Process (createProcess, shell, CreateProcess(cwd), waitForProcess)
import System.Directory (makeAbsolute, createDirectoryIfMissing, copyFile)
import System.FilePath (takeBaseName)

import Prelude hiding (writeFile)

handleAppendix :: HandlingarOps -> [Block] -> AppendixItem -> PandocIO [Block]
handleAppendix ops source_blocks (link_text, _, target) = do
    mxs <- handleBilaga ops source_blocks target
    case mxs of 
        Just xs -> do
            liftIO $ putStrLn $ "target: " ++ show target
            liftIO $ getWorkingDirectory >>= putStrLn
            case takeExtension . unpack $ target of
                "" -> return ()
                _  -> liftIO $ copyFile (unpack . T.drop 5 $ target) (destination ops </> (unpack . sourceToTarget' $ target))
            -- liftIO $ catch (copyFile (unpack target) (destination ops </> (unpack . sourceToTarget' $ target))) (\_ -> (copyFile (unpack target <> ".wiki") (destination ops </> (unpack . sourceToTarget' $ target))))

            liftIO $ print xs
            -- template' <- getTemplate "html.template"
            -- res' <- compileTemplate "html.template" template'
            res' <- liftIO $ compileTemplateFile "/home/hugo/code/vimwiki-scripts/hs/html.template"
            let res = case res' of
                                Left _ -> Nothing
                                Right x -> Just x
            liftIO . putStrLn $ "template: " ++ show res
            -- let template = renderTemplate templateData
            out <- writeHtml5String (def { writerTemplate = res }) (Pandoc (Meta Map.empty) xs)
            liftIO $ writeFile (destination ops </> (unpack . sourceToTarget $ target))
                               (out)
                               -- (pack . show $ xs)
            return []
        Nothing -> return []

sourceToTarget' :: Text -> Text
sourceToTarget' source
  | "file:" == T.take 5 source = proc $ T.drop 5 source
  | otherwise                  = proc source
  where proc s = T.replace "/" "-" s

-- Convert a link wikilink from the source document to an html link in
-- the destination document
sourceToTarget :: Text -> Text
sourceToTarget source = sourceToTarget' source <> ".html"

rewriteLinkHtml :: Inline -> State [AppendixItem] Inline
rewriteLinkHtml x@(Link _ displayed (target, "wikilink")) = do
    modify ((displayed, "", target):)
    return $ Link ("", [], []) 
                  (displayed <> [Superscript [Str "(bilaga)"]])
                  (sourceToTarget target, "") -- TODO write something nice for title
rewriteLinkHtml x = return x

-- TODO this is probably where we should create the included files
handleFileHtml :: FilePath -> String -> PandocIO (Maybe [Block])
handleFileHtml fname ".tex" = do
    aname <- liftIO $ makeAbsolute fname
    let dest = "/tmp/vimwiki-script/" ++ (takeBaseName aname)
    liftIO $ createDirectoryIfMissing True dest
    liftIO (copyFile aname $ dest ++ "/doc.tex")
    (_, _, _, handle) <- liftIO $ createProcess ((shell "latexmk -pdf doc") { cwd = Just dest })
    liftIO $ waitForProcess handle
    handleFileHtml (dest ++ "/doc.pdf") ".pdf"
handleFileHtml fname ".pdf" = return . Just $ [ Plain [ RawInline (Format "html") ("<object type=\"application/pdf\" data=\"" <> (sourceToTarget' . pack $ fname) <> "\">PDF Failed loading</object>") ] ]
handleFileHtml fname _ = do
    dat <- liftIO $ readFile fname
    return . Just $ [ Plain [ Code ("", [], []) (pack dat) ]]
    

handleHtml :: Text -> String -> FilePath -> PandocIO ()
handleHtml source_text heading destination = do
  let ops = HandlingarOps { handleFile = handleFileHtml
                          , rewriteLink = rewriteLinkHtml
                          , destination = destination
                          }

  Pandoc m' og_bs <- readVimwiki def source_text
  let Just better_blocks = getHeadingData (pack heading) og_bs
  (Pandoc meta bs, appendices) <- buildPrimary ops (Pandoc m' better_blocks)

  liftIO $ putStrLn $ "meta: " ++ show meta
  liftIO $ putStrLn $ "count appendies: " ++ show (length appendices)
  -- liftIO $ putStrLn $ "count appendies: " ++ show appendices

  fragments <- mapM (handleAppendix ops og_bs) $ reverse appendices
  let apx = mconcat fragments
  liftIO $ putStrLn $ "apx: " ++ show apx
  let content = Pandoc meta bs

  res' <- liftIO $ compileTemplateFile "/home/hugo/code/vimwiki-scripts/hs/html.template"
  let res = case res' of
                      Left _ -> Nothing
                      Right x -> Just x
  result <- writeHtml5String (def { writerTemplate = res }) content
  liftIO $ writeFile (destination </> "index.html") result