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

-- |

-- Module      : $header$

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

-- 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 Renderer
matplotlib :: PlotM Renderer
matplotlib = do
  Text
cmdargs <- forall a. (Configuration -> a) -> PlotM a
asksConfig Configuration -> Text
matplotlibCmdArgs
  forall (m :: * -> *) a. Monad m => a -> m a
return
    forall a b. (a -> b) -> a -> b
$ Renderer
      { rendererToolkit :: Toolkit
rendererToolkit = Toolkit
Matplotlib,
        rendererCapture :: FigureSpec -> String -> Text
rendererCapture = FigureSpec -> String -> Text
matplotlibCapture,
        rendererCommand :: OutputSpec -> Text
rendererCommand = Text -> OutputSpec -> Text
matplotlibCommand Text
cmdargs,
        rendererAvailability :: AvailabilityCheck
rendererAvailability = (Executable -> Text) -> AvailabilityCheck
CommandSuccess forall a b. (a -> b) -> a -> b
$ \Executable
exe -> [st|#{pathToExe exe} -c "import matplotlib"|],
        rendererSupportedSaveFormats :: [SaveFormat]
rendererSupportedSaveFormats = [SaveFormat]
matplotlibSupportedSaveFormats,
        rendererChecks :: [Text -> CheckResult]
rendererChecks = [Text -> CheckResult
matplotlibCheckIfShow],
        rendererLanguage :: Text
rendererLanguage = Text
"python",
        rendererComment :: Text -> Text
rendererComment = forall a. Monoid a => a -> a -> a
mappend Text
"# ",
        rendererScriptExtension :: String
rendererScriptExtension = String
".py"
      }

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

matplotlibCommand :: Text -> OutputSpec -> Text
matplotlibCommand :: Text -> OutputSpec -> Text
matplotlibCommand Text
cmdargs OutputSpec {String
FigureSpec
Executable
oCWD :: OutputSpec -> String
oExecutable :: OutputSpec -> Executable
oFigurePath :: OutputSpec -> String
oScriptPath :: OutputSpec -> String
oFigureSpec :: OutputSpec -> FigureSpec
oCWD :: String
oExecutable :: Executable
oFigurePath :: String
oScriptPath :: String
oFigureSpec :: FigureSpec
..} = [st|#{pathToExe oExecutable} #{cmdargs} "#{oScriptPath}"|]

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

matplotlibCaptureFragment :: FigureSpec -> FilePath -> Script
matplotlibCaptureFragment :: FigureSpec -> String -> Text
matplotlibCaptureFragment FigureSpec {Bool
Int
String
[String]
[(Text, Text)]
Attr
Text
Renderer
SaveFormat
Executable
blockAttrs :: FigureSpec -> Attr
extraAttrs :: FigureSpec -> [(Text, Text)]
dependencies :: FigureSpec -> [String]
dpi :: FigureSpec -> Int
directory :: FigureSpec -> String
saveFormat :: FigureSpec -> SaveFormat
script :: FigureSpec -> Text
withSource :: FigureSpec -> Bool
caption :: FigureSpec -> Text
fsExecutable :: FigureSpec -> Executable
renderer_ :: FigureSpec -> Renderer
blockAttrs :: Attr
extraAttrs :: [(Text, Text)]
dependencies :: [String]
dpi :: Int
directory :: String
saveFormat :: SaveFormat
script :: Text
withSource :: Bool
caption :: Text
fsExecutable :: Executable
renderer_ :: Renderer
..} String
fname =
  [st|
import matplotlib.pyplot as plt
plt.savefig(r"#{fname}", dpi=#{dpi}, transparent=#{transparent}, bbox_inches=#{tightBox})
|]
  where
    attrs :: Map Text Text
attrs = forall k a. Ord k => [(k, a)] -> Map k a
M.fromList [(Text, Text)]
extraAttrs
    tight_ :: Bool
tight_ = Text -> Bool
readBool forall a b. (a -> b) -> a -> b
$ forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault Text
"False" (String -> Text
T.pack forall a b. (a -> b) -> a -> b
$ forall a. Show a => a -> String
show InclusionKey
MatplotlibTightBBoxK) Map Text Text
attrs
    transparent_ :: Bool
transparent_ = Text -> Bool
readBool forall a b. (a -> b) -> a -> b
$ forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault Text
"False" (String -> Text
T.pack forall a b. (a -> b) -> a -> b
$ forall a. Show a => a -> String
show InclusionKey
MatplotlibTransparentK) 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)

-- | 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 forall a b. (a -> b) -> a -> b
$ forall a. Monoid a => [a] -> a
mconcat [Any]
showPresent
    then Text -> CheckResult
CheckFailed Text
"encountered a call to `matplotlib.pyplot.show` or `plt.show`, which would stall `pandoc-plot"
    else CheckResult
CheckPassed
  where
    showPresent :: [Any]
showPresent =
      (\Text
n -> Bool -> Any
Any (Text -> Text -> Bool
T.isInfixOf Text
n Text
s))
        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 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 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 = forall a. String -> a
errorWithoutStackTrace forall a b. (a -> b) -> a -> b
$ Text -> String
unpack forall a b. (a -> b) -> a -> b
$ forall a. Monoid a => [a] -> a
mconcat [Text
"Could not parse '", Text
s, Text
"' into a boolean. Please use 'True' or 'False'"]