{-# 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 SageMath figures

module Text.Pandoc.Filter.Plot.Renderers.SageMath
  ( sagemath,
    sagemathSupportedSaveFormats,
  )
where

import Text.Pandoc.Filter.Plot.Renderers.Prelude

sagemath :: PlotM (Maybe Renderer)
sagemath :: PlotM (Maybe Renderer)
sagemath = do
  Bool
avail <- PlotM Bool
sagemathAvailable
  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
sagemathCmdArgs
      Maybe Executable
mexe <- Toolkit -> PlotM (Maybe Executable)
executable Toolkit
SageMath
      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
SageMath,
                rendererExe :: Executable
rendererExe = Executable
exe,
                rendererCapture :: FigureSpec -> FilePath -> Text
rendererCapture = FigureSpec -> FilePath -> Text
sagemathCapture,
                rendererCommand :: OutputSpec -> Text
rendererCommand = Text -> Text -> OutputSpec -> Text
sagemathCommand Text
cmdargs Text
exename,
                rendererSupportedSaveFormats :: [SaveFormat]
rendererSupportedSaveFormats = [SaveFormat]
sagemathSupportedSaveFormats,
                rendererChecks :: [Text -> CheckResult]
rendererChecks = [Text -> CheckResult]
forall a. Monoid a => a
mempty,
                rendererLanguage :: Text
rendererLanguage = Text
"sagemath",
                rendererComment :: Text -> Text
rendererComment = Text -> Text -> Text
forall a. Monoid a => a -> a -> a
mappend Text
"# ",
                rendererScriptExtension :: FilePath
rendererScriptExtension = FilePath
".sage"
              }

-- See here:

-- https://doc.sagemath.org/html/en/reference/plotting/sage/plot/graphics.html#sage.plot.graphics.Graphics.save

sagemathSupportedSaveFormats :: [SaveFormat]
sagemathSupportedSaveFormats :: [SaveFormat]
sagemathSupportedSaveFormats = [SaveFormat
EPS, SaveFormat
PDF, SaveFormat
PNG, SaveFormat
SVG]

sagemathCommand :: Text -> Text -> OutputSpec -> Text
sagemathCommand :: Text -> Text -> OutputSpec -> Text
sagemathCommand 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}"|]

sagemathAvailable :: PlotM Bool
sagemathAvailable :: PlotM Bool
sagemathAvailable = do
  Maybe Executable
mexe <- Toolkit -> PlotM (Maybe Executable)
executable Toolkit
SageMath
  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) -> do
      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} -v|]


sagemathCapture :: FigureSpec -> FilePath -> Script
sagemathCapture :: FigureSpec -> FilePath -> Text
sagemathCapture = (FigureSpec -> FilePath -> Text) -> FigureSpec -> FilePath -> Text
appendCapture FigureSpec -> FilePath -> Text
sagemathCaptureFragment


-- This capture fragment is a bit ugly because sage does not have the

-- equivalent of matplotlib's `plt.gca()` to get a pointer to the most

-- recent graphical object. We must search for it

sagemathCaptureFragment :: FigureSpec -> FilePath -> Script
sagemathCaptureFragment :: FigureSpec -> FilePath -> Text
sagemathCaptureFragment 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 sage.plot.graphics as go
import sage.plot.plot3d.base as go3d
import builtins
# Try to concatenate 3D graphics objects first; if this doesn't work, then 
# concatenate all 2D graphic objects.
__all_graphics = builtins.sum( (obj for obj in globals().values() if isinstance(obj, go3d.Graphics3d)))
if not __all_graphics:
    __all_graphics = builtins.sum( (obj for obj in globals().values() if isinstance(obj, go.Graphics)))
if not __all_graphics:
    raise RuntimeError(''.join([
        "No plotting objects detected. ",
        "Make sure that all of your plotting objects are named, e.g. `G = plot(...)` rather than just `plot(...)`. ",
        "This is a limitation specific to the interaction between sage and pandoc-plot."
    ]))
__all_graphics.save_image(r"#{fname}", dpi=#{dpi})
|]