{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE NoImplicitPrelude #-}

-- |

-- Module      : $header$

-- Copyright   : (c) Laurent P René de Cotret, 2019 - 2021

-- License     : GNU GPL, version 2 or above

-- Maintainer  : laurent.decotret@outlook.com

-- Stability   : internal

-- Portability : portable

--

-- Rendering Matplotlib code blocks.

--

-- Note that the MatplotlibM renderer supports two extra arguments:

--     * @tight_bbox=True|False@ : Make plot bounding box tight. Default is False

--     * @transparent=True|False@ : Make plot background transparent (perfect for web pages). Default is False.

module Text.Pandoc.Filter.Plot.Renderers.Matplotlib
  ( matplotlib,
    matplotlibSupportedSaveFormats,
  )
where

import qualified Data.Map.Strict as M
import Data.Monoid (Any (..))
import qualified Data.Text as T
import Text.Pandoc.Filter.Plot.Renderers.Prelude

matplotlib :: PlotM (Maybe Renderer)
matplotlib :: PlotM (Maybe Renderer)
matplotlib = do
  Bool
avail <- PlotM Bool
matplotlibAvailable
  if Bool -> Bool
not Bool
avail
    then Maybe Renderer -> PlotM (Maybe Renderer)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe Renderer
forall a. Maybe a
Nothing
    else do
      Text
cmdargs <- (Configuration -> Text) -> PlotM Text
forall a. (Configuration -> a) -> PlotM a
asksConfig Configuration -> Text
matplotlibCmdArgs
      Maybe Executable
mexe <- Toolkit -> PlotM (Maybe Executable)
executable Toolkit
Matplotlib
      Maybe Renderer -> PlotM (Maybe Renderer)
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe Renderer -> PlotM (Maybe Renderer))
-> Maybe Renderer -> PlotM (Maybe Renderer)
forall a b. (a -> b) -> a -> b
$
        Maybe Executable
mexe Maybe Executable
-> (Executable -> Maybe Renderer) -> Maybe Renderer
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \exe :: Executable
exe@(Executable FilePath
_ Text
exename) ->
          Renderer -> Maybe Renderer
forall (m :: * -> *) a. Monad m => a -> m a
return
            Renderer :: Toolkit
-> Executable
-> (FigureSpec -> FilePath -> Text)
-> (OutputSpec -> Text)
-> [SaveFormat]
-> [Text -> CheckResult]
-> Text
-> (Text -> Text)
-> FilePath
-> Renderer
Renderer
              { rendererToolkit :: Toolkit
rendererToolkit = Toolkit
Matplotlib,
                rendererExe :: Executable
rendererExe = Executable
exe,
                rendererCapture :: FigureSpec -> FilePath -> Text
rendererCapture = FigureSpec -> FilePath -> Text
matplotlibCapture,
                rendererCommand :: OutputSpec -> Text
rendererCommand = Text -> Text -> OutputSpec -> Text
matplotlibCommand Text
cmdargs Text
exename,
                rendererSupportedSaveFormats :: [SaveFormat]
rendererSupportedSaveFormats = [SaveFormat]
matplotlibSupportedSaveFormats,
                rendererChecks :: [Text -> CheckResult]
rendererChecks = [Text -> CheckResult
matplotlibCheckIfShow],
                rendererLanguage :: Text
rendererLanguage = Text
"python",
                rendererComment :: Text -> Text
rendererComment = Text -> Text -> Text
forall a. Monoid a => a -> a -> a
mappend Text
"# ",
                rendererScriptExtension :: FilePath
rendererScriptExtension = FilePath
".py"
              }

matplotlibSupportedSaveFormats :: [SaveFormat]
matplotlibSupportedSaveFormats :: [SaveFormat]
matplotlibSupportedSaveFormats = [SaveFormat
PNG, SaveFormat
PDF, SaveFormat
SVG, SaveFormat
JPG, SaveFormat
EPS, SaveFormat
GIF, SaveFormat
TIF]

matplotlibCommand :: Text -> Text -> OutputSpec -> Text
matplotlibCommand :: Text -> Text -> OutputSpec -> Text
matplotlibCommand Text
cmdargs Text
exe OutputSpec {FilePath
FigureSpec
oCWD :: OutputSpec -> FilePath
oFigurePath :: OutputSpec -> FilePath
oScriptPath :: OutputSpec -> FilePath
oFigureSpec :: OutputSpec -> FigureSpec
oCWD :: FilePath
oFigurePath :: FilePath
oScriptPath :: FilePath
oFigureSpec :: FigureSpec
..} = [st|#{exe} #{cmdargs} "#{oScriptPath}"|]

matplotlibCapture :: FigureSpec -> FilePath -> Script
matplotlibCapture :: FigureSpec -> FilePath -> Text
matplotlibCapture = (FigureSpec -> FilePath -> Text) -> FigureSpec -> FilePath -> Text
appendCapture FigureSpec -> FilePath -> Text
matplotlibCaptureFragment

matplotlibCaptureFragment :: FigureSpec -> FilePath -> Script
matplotlibCaptureFragment :: FigureSpec -> FilePath -> Text
matplotlibCaptureFragment FigureSpec {Bool
Int
FilePath
[FilePath]
[(Text, Text)]
Attr
Text
Renderer
SaveFormat
blockAttrs :: FigureSpec -> Attr
extraAttrs :: FigureSpec -> [(Text, Text)]
dependencies :: FigureSpec -> [FilePath]
dpi :: FigureSpec -> Int
directory :: FigureSpec -> FilePath
saveFormat :: FigureSpec -> SaveFormat
script :: FigureSpec -> Text
withSource :: FigureSpec -> Bool
caption :: FigureSpec -> Text
renderer_ :: FigureSpec -> Renderer
blockAttrs :: Attr
extraAttrs :: [(Text, Text)]
dependencies :: [FilePath]
dpi :: Int
directory :: FilePath
saveFormat :: SaveFormat
script :: Text
withSource :: Bool
caption :: Text
renderer_ :: Renderer
..} FilePath
fname =
  [st|
import matplotlib.pyplot as plt
plt.savefig(r"#{fname}", dpi=#{dpi}, transparent=#{transparent}, bbox_inches=#{tightBox})
|]
  where
    attrs :: Map Text Text
attrs = [(Text, Text)] -> Map Text Text
forall k a. Ord k => [(k, a)] -> Map k a
M.fromList [(Text, Text)]
extraAttrs
    tight_ :: Bool
tight_ = Text -> Bool
readBool (Text -> Bool) -> Text -> Bool
forall a b. (a -> b) -> a -> b
$ Text -> Text -> Map Text Text -> Text
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault Text
"False" Text
"tight" Map Text Text
attrs
    transparent_ :: Bool
transparent_ = Text -> Bool
readBool (Text -> Bool) -> Text -> Bool
forall a b. (a -> b) -> a -> b
$ Text -> Text -> Map Text Text -> Text
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault Text
"False" Text
"transparent" Map Text Text
attrs
    tightBox :: Text
tightBox = if Bool
tight_ then (Text
"'tight'" :: Text) else (Text
"None" :: Text)
    transparent :: Text
transparent = if Bool
transparent_ then (Text
"True" :: Text) else (Text
"False" :: Text)

matplotlibAvailable :: PlotM Bool
matplotlibAvailable :: PlotM Bool
matplotlibAvailable = do
  Maybe Executable
mexe <- Toolkit -> PlotM (Maybe Executable)
executable Toolkit
Matplotlib
  case Maybe Executable
mexe of
    Maybe Executable
Nothing -> Bool -> PlotM Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False
    Just (Executable FilePath
dir Text
exe) ->
      FilePath -> PlotM Bool -> PlotM Bool
forall a. FilePath -> PlotM a -> PlotM a
withPrependedPath FilePath
dir (PlotM Bool -> PlotM Bool) -> PlotM Bool -> PlotM Bool
forall a b. (a -> b) -> a -> b
$ (RuntimeEnv -> FilePath)
-> StateT PlotState (ReaderT RuntimeEnv IO) FilePath
forall r (m :: * -> *) a. MonadReader r m => (r -> a) -> m a
asks RuntimeEnv -> FilePath
envCWD StateT PlotState (ReaderT RuntimeEnv IO) FilePath
-> (FilePath -> PlotM Bool) -> PlotM Bool
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (FilePath -> Text -> PlotM Bool) -> Text -> FilePath -> PlotM Bool
forall a b c. (a -> b -> c) -> b -> a -> c
flip FilePath -> Text -> PlotM Bool
commandSuccess [st|#{exe} -c "import matplotlib"|]

-- | Check if `matplotlib.pyplot.show()` calls are present in the script,

-- which would halt pandoc-plot

matplotlibCheckIfShow :: Script -> CheckResult
matplotlibCheckIfShow :: Text -> CheckResult
matplotlibCheckIfShow Text
s =
  if Any -> Bool
getAny (Any -> Bool) -> Any -> Bool
forall a b. (a -> b) -> a -> b
$ [Any] -> Any
forall a. Monoid a => [a] -> a
mconcat [Any]
showPresent
    then Text -> CheckResult
CheckFailed Text
"encountered a call to `matplotlib.pyplot.show`."
    else CheckResult
CheckPassed
  where
    showPresent :: [Any]
showPresent =
      (\Text
n -> Bool -> Any
Any (Text -> Text -> Bool
T.isInfixOf Text
n Text
s))
        (Text -> Any) -> [Text] -> [Any]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [ Text
"matplotlib.pyplot.show()",
              Text
"pyplot.show()",
              Text
"plt.show()"
            ]

-- | Flexible boolean parsing

readBool :: Text -> Bool
readBool :: Text -> Bool
readBool Text
s
  | Text
s Text -> [Text] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Text
"True", Text
"true", Text
"'True'", Text
"'true'", Text
"1"] = Bool
True
  | Text
s Text -> [Text] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Text
"False", Text
"false", Text
"'False'", Text
"'false'", Text
"0"] = Bool
False
  | Bool
otherwise = FilePath -> Bool
forall a. FilePath -> a
errorWithoutStackTrace (FilePath -> Bool) -> FilePath -> Bool
forall a b. (a -> b) -> a -> b
$ Text -> FilePath
unpack (Text -> FilePath) -> Text -> FilePath
forall a b. (a -> b) -> a -> b
$ [Text] -> Text
forall a. Monoid a => [a] -> a
mconcat [Text
"Could not parse '", Text
s, Text
"' into a boolean. Please use 'True' or 'False'"]