{-# 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 Bokeh code blocks

module Text.Pandoc.Filter.Plot.Renderers.Bokeh
  ( bokeh,
    bokehSupportedSaveFormats,
  )
where

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

bokeh :: PlotM (Maybe Renderer)
bokeh :: PlotM (Maybe Renderer)
bokeh = do
  Bool
avail <- PlotM Bool
bokehAvailable
  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
bokehCmdArgs
      Maybe Executable
mexe <- Toolkit -> PlotM (Maybe Executable)
executable Toolkit
Bokeh
      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
Bokeh,
                rendererExe :: Executable
rendererExe = Executable
exe,
                rendererCapture :: FigureSpec -> FilePath -> Text
rendererCapture = (FigureSpec -> FilePath -> Text) -> FigureSpec -> FilePath -> Text
appendCapture FigureSpec -> FilePath -> Text
bokehCaptureFragment,
                rendererCommand :: OutputSpec -> Text
rendererCommand = Text -> Text -> OutputSpec -> Text
bokehCommand Text
cmdargs Text
exename,
                rendererSupportedSaveFormats :: [SaveFormat]
rendererSupportedSaveFormats = [SaveFormat]
bokehSupportedSaveFormats,
                rendererChecks :: [Text -> CheckResult]
rendererChecks = [Text -> CheckResult
bokehCheckIfShow],
                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"
              }

bokehSupportedSaveFormats :: [SaveFormat]
bokehSupportedSaveFormats :: [SaveFormat]
bokehSupportedSaveFormats = [SaveFormat
PNG, SaveFormat
SVG, SaveFormat
HTML]

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

bokehAvailable :: PlotM Bool
bokehAvailable :: PlotM Bool
bokehAvailable = do
  Maybe Executable
mexe <- Toolkit -> PlotM (Maybe Executable)
executable Toolkit
Bokeh
  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 bokeh; import selenium"|]

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

-- which would halt pandoc-plot

bokehCheckIfShow :: Script -> CheckResult
bokehCheckIfShow :: Text -> CheckResult
bokehCheckIfShow 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 `bokeh.io.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
"bokeh.io.show(",
              Text
"show("
            ]

bokehCaptureFragment :: FigureSpec -> FilePath -> Script
bokehCaptureFragment :: FigureSpec -> FilePath -> Text
bokehCaptureFragment 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|
from bokeh.io import export_png, export_svgs, save
from bokeh.models import Model
from bokeh.resources import CDN

# The heuristic to determine the current Model is to find all objects which are
# at least subclasses of bokeh.models.Model, and then find the one which was
# created last. This is a dirty hack, so if you're reading this, don't hesitate to
# suggest something else.
__current_model = [obj for obj in globals().values() if isinstance(obj, Model)][-1]
#{write}
|]
  where
    write :: Text
write = case SaveFormat
saveFormat of
      SaveFormat
HTML -> [st|save(__current_model, filename=r"#{fname}", resources=CDN)|]
      SaveFormat
SVG -> [st|__current_model.output_backend="svg"; export_svgs(__current_model, filename=r"#{fname}")|]
      SaveFormat
PNG -> [st|export_png(obj = __current_model, filename=r"#{fname}")|]
      SaveFormat
fmt -> FilePath -> Text
forall a. FilePath -> a
errorWithoutStackTrace (FilePath -> Text) -> FilePath -> Text
forall a b. (a -> b) -> a -> b
$ FilePath
"Save format not supported: " FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<> SaveFormat -> FilePath
forall a. Show a => a -> FilePath
show SaveFormat
fmt