{-# 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 Plotly/R plots code blocks

module Text.Pandoc.Filter.Plot.Renderers.PlotlyR
  ( plotlyR,
    plotlyRSupportedSaveFormats,
  )
where

import qualified Data.Text as T
import Text.Pandoc.Filter.Plot.Renderers.Prelude

plotlyR :: PlotM (Maybe Renderer)
plotlyR :: PlotM (Maybe Renderer)
plotlyR = do
  Bool
avail <- PlotM Bool
plotlyRAvailable
  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
plotlyRCmdArgs
      Maybe Executable
mexe <- Toolkit -> PlotM (Maybe Executable)
executable Toolkit
PlotlyR
      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
PlotlyR,
                rendererExe :: Executable
rendererExe = Executable
exe,
                rendererCapture :: FigureSpec -> FilePath -> Text
rendererCapture = FigureSpec -> FilePath -> Text
plotlyRCapture,
                rendererCommand :: OutputSpec -> Text
rendererCommand = Text -> Text -> OutputSpec -> Text
plotlyRCommand Text
cmdargs Text
exename,
                rendererSupportedSaveFormats :: [SaveFormat]
rendererSupportedSaveFormats = [SaveFormat]
plotlyRSupportedSaveFormats,
                rendererChecks :: [Text -> CheckResult]
rendererChecks = [Text -> CheckResult]
forall a. Monoid a => a
mempty,
                rendererLanguage :: Text
rendererLanguage = Text
"r",
                rendererComment :: Text -> Text
rendererComment = Text -> Text -> Text
forall a. Monoid a => a -> a -> a
mappend Text
"# ",
                rendererScriptExtension :: FilePath
rendererScriptExtension = FilePath
".r"
              }

plotlyRSupportedSaveFormats :: [SaveFormat]
plotlyRSupportedSaveFormats :: [SaveFormat]
plotlyRSupportedSaveFormats = [SaveFormat
PNG, SaveFormat
PDF, SaveFormat
SVG, SaveFormat
JPG, SaveFormat
EPS, SaveFormat
HTML]

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

plotlyRAvailable :: PlotM Bool
plotlyRAvailable :: PlotM Bool
plotlyRAvailable = do
  Maybe Executable
mexe <- Toolkit -> PlotM (Maybe Executable)
executable Toolkit
PlotlyR
  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} -e "if(!require('plotly')) {quit(status=1)}"|]

plotlyRCapture :: FigureSpec -> FilePath -> Script
plotlyRCapture :: FigureSpec -> FilePath -> Text
plotlyRCapture FigureSpec
fs FilePath
fp =
  [Text] -> Text
T.unlines
    [ Text
"pdf(NULL)", -- Prevent the creation of empty Rplots.pdf

      FigureSpec -> Text
script FigureSpec
fs,
      FigureSpec -> FilePath -> Text
plotlyRCaptureFragment FigureSpec
fs FilePath
fp
    ]

plotlyRCaptureFragment :: FigureSpec -> FilePath -> Script
plotlyRCaptureFragment :: FigureSpec -> FilePath -> Text
plotlyRCaptureFragment spec :: FigureSpec
spec@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
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
script :: FigureSpec -> Text
..} FilePath
fname = case SaveFormat
saveFormat of
  SaveFormat
HTML -> FigureSpec -> FilePath -> Text
plotlyRCaptureHtml FigureSpec
spec FilePath
fname
  SaveFormat
_ -> FigureSpec -> FilePath -> Text
plotlyRCaptureStatic FigureSpec
spec FilePath
fname

-- Based on the following discussion:

--    https://stackoverflow.com/q/34580095

plotlyRCaptureHtml :: FigureSpec -> FilePath -> Script
plotlyRCaptureHtml :: FigureSpec -> FilePath -> Text
plotlyRCaptureHtml FigureSpec
_ FilePath
fname =
  [st|
library(plotly) # just in case
library(htmlwidgets)
p <- last_plot()
htmlwidgets::saveWidget(as_widget(p), "#{toRPath fname}")
|]

-- Based on the following documentation:

--    https://plotly.com/r/static-image-export/

plotlyRCaptureStatic :: FigureSpec -> FilePath -> Script
plotlyRCaptureStatic :: FigureSpec -> FilePath -> Text
plotlyRCaptureStatic FigureSpec
_ FilePath
fname =
  [st|
library(plotly) # just in case
if (!require("processx")) install.packages("processx")
pdf(NULL)
orca(last_plot(), file = "#{toRPath fname}")
|]