@@ -28,26 +28,23 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
2828
2929Conversion of 'Pandoc' documents to EPUB.
3030-}
31−module Text.Pandoc.Writers.EPUB ( writeEPUB ) where
32−import Data.IORef ( IORef, newIORef, readIORef, modifyIORef )
31+module Text.Pandoc.Writers.EPUB ( writeEPUB, writeEPUBPure ) where
32+import Data.IORef ( IORef )
3333import qualified Data.Map as M
3434import qualified Data.Set as Set
3535import Data.Maybe ( fromMaybe, catMaybes )
3636import Data.List ( isPrefixOf, isInfixOf, intercalate )
37−import System.Environment ( getEnv )
3837import Text.Printf (printf)
3938import System.FilePath ( takeExtension, takeFileName )
40−import System.FilePath.Glob ( namesMatching )
4139import Network.HTTP ( urlEncode )
4240import qualified Data.ByteString.Lazy as B
4341import qualified Data.ByteString.Lazy.Char8 as B8
4442import qualified Text.Pandoc.UTF8 as UTF8
4543import Codec.Archive.Zip ( emptyArchive, addEntryToArchive, eRelativePath, fromEntry , Entry, toEntry, fromArchive)
46−import Data.Time.Clock.POSIX ( getPOSIXTime )
4744import Text.Pandoc.Compat.Time
4845import Text.Pandoc.Shared ( renderTags', safeRead, uniqueIdent, trim
49− , normalizeDate, readDataFile, stringify, warn
50− , hierarchicalize, fetchItem' )
46+ , normalizeDate, stringify
47+ , hierarchicalize )
5148import qualified Text.Pandoc.Shared as S (Element(..))
5249import Text.Pandoc.Builder (fromList, setMeta)
5350import Text.Pandoc.Options ( WriterOptions(..)
@@ -58,17 +55,19 @@ import Text.Pandoc.Options ( WriterOptions(..)
5855import Text.Pandoc.Definition
5956import Text.Pandoc.Walk (walk, walkM, query)
6057import Control.Monad.State (modify, get, State, put, evalState)
61−import Control.Monad (mplus, liftM, when)
58+import Control.Monad (mplus, when)
6259import Text.XML.Light ( unode, Element(..), unqual, Attr(..), add_attrs
6360 , strContent, lookupAttr, Node(..), QName(..), parseXML
6461 , onlyElems, node, ppElement)
65−import Text.Pandoc.UUID (getRandomUUID)
6662import Text.Pandoc.Writers.HTML ( writeHtml )
6763import Data.Char ( toLower, isDigit, isAlphaNum )
6864import Text.Pandoc.MIME (MimeType, getMimeType, extensionFromMimeType)
69−import qualified Control.Exception as E
7065import Text.Blaze.Html.Renderer.Utf8 (renderHtml)
7166import Text.HTML.TagSoup (Tag(TagOpen), fromAttrib, parseTags)
67+import Text.Pandoc.Free (PandocAction, runIO)
68+import qualified Text.Pandoc.Free as P
69+
70+type EPUBAction = PandocAction [(FilePath, (FilePath, Maybe Entry))]
7271
7372-- A Chapter includes a list of blocks and maybe a section
7473-- number offset. Note, some chapters are unnumbered. The section
@@ -143,7 +142,7 @@ removeNote :: Inline -> Inline
143142removeNote (Note _) = Str ""
144143removeNote x = x
145144
146−getEPUBMetadata :: WriterOptions -> Meta -> IO EPUBMetadata
145+getEPUBMetadata :: WriterOptions -> Meta -> EPUBAction EPUBMetadata
147146getEPUBMetadata opts meta = do
148147 let md = metadataFromMeta opts meta
149148 let elts = onlyElems $ parseXML $ writerEpubMetadata opts
@@ -151,7 +150,7 @@ getEPUBMetadata opts meta = do
151150 let addIdentifier m =
152151 if null (epubIdentifier m)
153152 then do
154− randomId <- fmap show getRandomUUID
153+ randomId <- fmap show P.newUUID
155154 return $ m{ epubIdentifier = [Identifier randomId Nothing] }
156155 else return m
157156 let addLanguage m =
@@ -159,16 +158,19 @@ getEPUBMetadata opts meta = do
159158 then case lookup "lang" (writerVariables opts) of
160159 Just x -> return m{ epubLanguage = x }
161160 Nothing -> do
162− localeLang <- E.catch (liftM
163− (map (\c -> if c == '_' then '-' else c) .
164− takeWhile (/='.')) $ getEnv "LANG")
165− (\e -> let _ = (e :: E.SomeException) in return "en-US")
161+ mLang <- P.lookupEnv "LANG"
162+ let localeLang =
163+ case mLang of
164+ Just lang ->
165+ map (\c -> if c == '_' then '-' else c) $
166+ takeWhile (/='.') lang
167+ Nothing -> "en-US"
166168 return m{ epubLanguage = localeLang }
167169 else return m
168170 let fixDate m =
169171 if null (epubDate m)
170172 then do
171− currentTime <- getCurrentTime
173+ currentTime <- P.getCurrentTime
172174 return $ m{ epubDate = [ Date{
173175 dateText = showDateTimeISO8601 currentTime
174176 , dateEvent = Nothing } ] }
@@ -333,10 +335,15 @@ metadataFromMeta opts meta = EPUBMetadata{
333335writeEPUB :: WriterOptions -- ^ Writer options
334336 -> Pandoc -- ^ Document to convert
335337 -> IO B.ByteString
336−writeEPUB opts doc@(Pandoc meta _) = do
338+writeEPUB opts doc = runIO $ writeEPUBPure opts doc
339+
340+writeEPUBPure :: WriterOptions -- ^ Writer options
341+ -> Pandoc -- ^ Document to convert
342+ -> EPUBAction B.ByteString
343+writeEPUBPure opts doc@(Pandoc meta _) = do
337344 let version = fromMaybe EPUB2 (writerEpubVersion opts)
338345 let epub3 = version == EPUB3
339− epochtime <- floor `fmap` getPOSIXTime
346+ epochtime <- floor <$> P.getPOSIXTime
340347 let mkEntry path content = toEntry path epochtime content
341348 let vars = ("epub3", if epub3 then "true" else "false")
342349 : ("css", "stylesheet.css")
@@ -361,7 +368,7 @@ writeEPUB opts doc@(Pandoc meta _) = do
361368 let cpContent = renderHtml $ writeHtml
362369 opts'{ writerVariables = ("coverpage","true"):vars }
363370 (Pandoc meta [RawBlock (Format "html") $ "<div id=\"cover-image\">\n<img src=\"" ++ coverImage ++ "\" alt=\"cover image\" />\n</div>"])
364− imgContent <- B.readFile img
371+ imgContent <- P.readFileLazy img
365372 return ( [mkEntry "cover.xhtml" cpContent]
366373 , [mkEntry coverImage imgContent] )
367374
@@ -372,18 +379,18 @@ writeEPUB opts doc@(Pandoc meta _) = do
372379 let tpEntry = mkEntry "title_page.xhtml" tpContent
373380
374381 -- handle pictures
375− mediaRef <- newIORef []
382+ mediaRef <- P.newIORef []
376383 Pandoc _ blocks <- walkM (transformInline opts' mediaRef) doc >>=
377384 walkM (transformBlock opts' mediaRef)
378− picEntries <- (catMaybes . map (snd . snd)) <$> readIORef mediaRef
385+ picEntries <- (catMaybes . map (snd . snd)) <$> P.readIORef mediaRef
379386
380387 -- handle fonts
381388 let matchingGlob f = do
382− xs <- namesMatching f
389+ xs <- P.namesMatching f
383390 when (null xs) $
384− warn $ f ++ " did not match any font files."
391+ P.warn $ f ++ " did not match any font files."
385392 return xs
386− let mkFontEntry f = mkEntry (takeFileName f) `fmap` B.readFile f
393+ let mkFontEntry f = mkEntry (takeFileName f) `fmap` P.readFileLazy f
387394 fontFiles <- concat <$> mapM matchingGlob (writerEpubFonts opts')
388395 fontEntries <- mapM mkFontEntry fontFiles
389396
@@ -520,7 +527,7 @@ writeEPUB opts doc@(Pandoc meta _) = do
520527 let uuid = case epubIdentifier metadata of
521528 (x:_) -> identifierText x -- use first identifier as UUID
522529 [] -> error "epubIdentifier is null" -- shouldn't happen
523− currentTime <- getCurrentTime
530+ currentTime <- P.getCurrentTime
524531 let contentsData = UTF8.fromStringLazy $ ppTopElement $
525532 unode "package" ! [("version", case version of
526533 EPUB2 -> "2.0"
@@ -692,10 +699,10 @@ writeEPUB opts doc@(Pandoc meta _) = do
692699
693700 -- stylesheet
694701 stylesheet <- case epubStylesheet metadata of
695− Just (StylesheetPath fp) -> UTF8.readFile fp
702+ Just (StylesheetPath fp) -> P.readFileUTF8 fp
696703 Just (StylesheetContents s) -> return s
697704 Nothing -> UTF8.toString `fmap`
698− readDataFile (writerUserDataDir opts) "epub.css"
705+ P.readDataFile (writerUserDataDir opts) "epub.css"
699706 let stylesheetEntry = mkEntry "stylesheet.css" $ UTF8.fromStringLazy stylesheet
700707
701708 -- construct archive
@@ -814,7 +821,7 @@ showDateTimeISO8601 = formatTime defaultTimeLocale "%FT%TZ"
814821transformTag :: WriterOptions
815822 -> IORef [(FilePath, (FilePath, Maybe Entry))] -- ^ (oldpath, newpath, entry) media
816823 -> Tag String
817− -> IO (Tag String)
824+ -> EPUBAction (Tag String)
818825transformTag opts mediaRef tag@(TagOpen name attr)
819826 | name `elem` ["video", "source", "img", "audio"] &&
820827 lookup "data-external" attr == Nothing = do
@@ -831,34 +838,34 @@ transformTag _ _ tag = return tag
831838modifyMediaRef :: WriterOptions
832839 -> IORef [(FilePath, (FilePath, Maybe Entry))]
833840 -> FilePath
834− -> IO FilePath
841+ -> EPUBAction FilePath
835842modifyMediaRef _ _ "" = return ""
836843modifyMediaRef opts mediaRef oldsrc = do
837− media <- readIORef mediaRef
844+ media <- P.readIORef mediaRef
838845 case lookup oldsrc media of
839846 Just (n,_) -> return n
840847 Nothing -> do
841− res <- fetchItem' (writerMediaBag opts)
848+ res <- P.fetchItem' (writerMediaBag opts)
842849 (writerSourceURL opts) oldsrc
843850 (new, mbEntry) <-
844851 case res of
845852 Left _ -> do
846− warn $ "Could not find media `" ++ oldsrc ++ "', skipping..."
853+ P.warn $ "Could not find media `" ++ oldsrc ++ "', skipping..."
847854 return (oldsrc, Nothing)
848855 Right (img,mbMime) -> do
849856 let new = "media/file" ++ show (length media) ++
850857 fromMaybe (takeExtension (takeWhile (/='?') oldsrc))
851858 (('.':) <$> (mbMime >>= extensionFromMimeType))
852− epochtime <- floor `fmap` getPOSIXTime
859+ epochtime <- floor `fmap` P.getPOSIXTime
853860 let entry = toEntry new epochtime $ B.fromChunks . (:[]) $ img
854861 return (new, Just entry)
855− modifyIORef mediaRef ( (oldsrc, (new, mbEntry)): )
862+ P.modifyIORef mediaRef ( (oldsrc, (new, mbEntry)): )
856863 return new
857864
858865transformBlock :: WriterOptions
859866 -> IORef [(FilePath, (FilePath, Maybe Entry))] -- ^ (oldpath, newpath, entry) media
860867 -> Block
861− -> IO Block
868+ -> EPUBAction Block
862869transformBlock opts mediaRef (RawBlock fmt raw)
863870 | fmt == Format "html" = do
864871 let tags = parseTags raw
@@ -869,7 +876,7 @@ transformBlock _ _ b = return b
869876transformInline :: WriterOptions
870877 -> IORef [(FilePath, (FilePath, Maybe Entry))] -- ^ (oldpath, newpath) media
871878 -> Inline
872− -> IO Inline
879+ -> EPUBAction Inline
873880transformInline opts mediaRef (Image attr lab (src,tit)) = do
874881 newsrc <- modifyMediaRef opts mediaRef src
875882 return $ Image attr lab (newsrc, tit)