{-# LANGUAGE OverloadedStrings #-}
module Text.Pandoc.Filter.FigureSpec
( FigureSpec(..)
, SaveFormat(..)
, saveFormatFromString
, figurePath
, hiresFigurePath
, addPlotCapture
, extension
) where
import Data.Hashable (Hashable, hash, hashWithSalt)
import qualified Data.Text as T
import System.FilePath (FilePath, addExtension,
replaceExtension, (</>))
import Text.Pandoc.Definition (Attr)
import Text.Pandoc.Filter.Scripting (PythonScript)
data SaveFormat
= PNG
| PDF
| SVG
| JPG
| EPS
saveFormatFromString :: String -> Maybe SaveFormat
saveFormatFromString s
| s `elem` ["png", "PNG", ".png"] = Just PNG
| s `elem` ["pdf", "PDF", ".pdf"] = Just PDF
| s `elem` ["svg", "SVG", ".svg"] = Just SVG
| s `elem` ["jpg", "jpeg", "JPG", "JPEG", ".jpg", ".jpeg"] = Just JPG
| s `elem` ["eps", "EPS", ".eps"] = Just EPS
| otherwise = Nothing
extension :: SaveFormat -> String
extension PNG = ".png"
extension PDF = ".pdf"
extension SVG = ".svg"
extension JPG = ".jpg"
extension EPS = ".eps"
data FigureSpec = FigureSpec
{ caption :: String
, script :: PythonScript
, saveFormat :: SaveFormat
, directory :: FilePath
, dpi :: Int
, blockAttrs :: Attr
}
instance Hashable FigureSpec where
hashWithSalt salt spec =
hashWithSalt salt (caption spec, script spec, directory spec, dpi spec, blockAttrs spec)
figurePath :: FigureSpec -> FilePath
figurePath spec = (directory spec </> stem spec)
where
stem = flip addExtension ext . show . hash
ext = extension . saveFormat $ spec
hiresFigurePath :: FigureSpec -> FilePath
hiresFigurePath spec = flip replaceExtension (".hires" <> ext) . figurePath $ spec
where
ext = extension . saveFormat $ spec
addPlotCapture ::
FigureSpec
-> PythonScript
addPlotCapture spec =
mconcat
[ script spec
, "\nimport matplotlib.pyplot as plt"
, plotCapture (figurePath spec) (dpi spec)
, plotCapture (hiresFigurePath spec) (minimum [200, 2 * dpi spec])
]
where
plotCapture fname' dpi' =
mconcat
[ "\nplt.savefig("
, T.pack $ show fname'
, ", dpi="
, T.pack $ show dpi'
, ")"
]