module Image.LaTeX.Render.Pandoc
(
convertFormulaDataURI
, convertAllFormulaeDataURI
, convertFormulaFiles
, convertAllFormulaeFiles
, NameSupply
, newNameSupply
, ShrinkSize
) where
import Text.Pandoc.Definition
import Text.Pandoc.Walk
import Image.LaTeX.Render
import Codec.Picture
import Control.Applicative
import Data.IORef
import System.FilePath
import qualified Data.ByteString.Base64.Lazy as B64
import qualified Data.ByteString.Lazy.Char8 as BS
dims :: Image a -> (Int,Int)
dims = liftA2 (,) imageWidth imageHeight
dimensions :: DynamicImage -> (Int,Int)
dimensions (ImageRGB8 i) = dims i
dimensions (ImageRGBA8 i) = dims i
dimensions (ImageRGB16 i) = dims i
dimensions (ImageRGBA16 i) = dims i
dimensions (ImageY8 i) = dims i
dimensions (ImageY16 i) = dims i
dimensions (ImageYA8 i) = dims i
dimensions (ImageYA16 i) = dims i
dimensions _ = error "Unsupported image format somehow!"
type ShrinkSize = Int
convertFormulaDataURI
:: ShrinkSize
-> EnvironmentOptions
-> (MathType -> FormulaOptions)
-> Inline -> IO Inline
convertFormulaDataURI sh o1 o2 (Math t s) = imageForFormula o1 (o2 t) s >>= \case
Left e -> return $ Str (show e)
Right (b,i) -> let
Right bs = encodeDynamicPng i
dataUri = "data:image/png;base64," ++ BS.unpack (B64.encode bs)
(ow,oh) = dimensions i
(w,h) = (ow `div` sh, oh `div` sh)
in return $ RawInline (Format "html") $
"<img width=" ++ show w ++
" height=" ++ show h ++
" src=\"" ++ dataUri ++ "\"" ++
" class=" ++ (case t of InlineMath -> "inline-math"; _ -> "display-math") ++
" style=\"margin:0; vertical-align:-" ++ show (b `div` sh) ++ "px;\"/>"
convertFormulaDataURI sh o1 o2 x = return x
convertAllFormulaeDataURI
:: ShrinkSize
-> EnvironmentOptions
-> (MathType -> FormulaOptions)
-> Pandoc -> IO Pandoc
convertAllFormulaeDataURI a b c = walkM $ convertFormulaDataURI a b c
type NameSupply = IORef Int
newNameSupply :: IO NameSupply
newNameSupply = newIORef 0
convertFormulaFiles
:: NameSupply
-> FilePath
-> ShrinkSize
-> EnvironmentOptions
-> (MathType -> FormulaOptions)
-> Inline -> IO Inline
convertFormulaFiles ns bn sh o1 o2 (Math t s) = imageForFormula o1 (o2 t) s >>= \case
Left e -> return $ Str (show e)
Right (b,i) -> do
fn <- readIORef ns
modifyIORef ns (+1)
let uri = bn </> show fn <.> "png"
(ow,oh) = dimensions i
(w,h) = (ow `div` sh, oh `div` sh)
_ <- writeDynamicPng uri i
return $ RawInline (Format "html") $
"<img width=" ++ show w ++
" height=" ++ show h ++
" src=\"" ++ uri ++ "\"" ++
" class=" ++ (case t of InlineMath -> "inline-math"; _ -> "display-math") ++
" style=\"margin:0; vertical-align:-" ++ show (b `div` sh) ++ "px;\"/>"
convertFormulaFiles _ _ _ _ _ x = return x
convertAllFormulaeFiles
:: NameSupply
-> FilePath
-> ShrinkSize
-> EnvironmentOptions
-> (MathType -> FormulaOptions)
-> Pandoc -> IO Pandoc
convertAllFormulaeFiles x y a b c = walkM $ convertFormulaFiles x y a b c