summaryrefslogtreecommitdiff
path: root/src/Text/Pandoc/Filter/Pyplot/Types.hs
blob: a0ab8f576b5b5ec9c95e5bf868b21b94ad9f37bd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
{-# LANGUAGE CPP               #-}
{-# LANGUAGE DeriveGeneric     #-}
{-# LANGUAGE OverloadedStrings #-}
{-|
Module      : $header$
Copyright   : (c) Laurent P René de Cotret, 2019
License     : GNU GPL, version 2 or above
Maintainer  : laurent.decotret@outlook.com
Stability   : internal
Portability : portable

This module defines types in use in pandoc-pyplot
-}

module Text.Pandoc.Filter.Pyplot.Types where

import           Control.Monad.Reader

import           Data.Char              (toLower)
import           Data.Default.Class     (Default, def)
import           Data.Hashable          (Hashable)
import           Data.List              (intersperse)
import           Data.Semigroup         as Sem
import           Data.String            (IsString(..))
import           Data.Text              (Text)
import           Data.Yaml              (ToJSON, object, toJSON, (.=))

import           GHC.Generics           (Generic)

import           Text.Pandoc.Definition (Attr)


-- | Keys that pandoc-pyplot will look for in code blocks. These are only exported for testing purposes.
directoryKey, captionKey, dpiKey, includePathKey, saveFormatKey, withLinksKey, isTightBboxKey, isTransparentKey :: Text
directoryKey     = "directory"
captionKey       = "caption"
dpiKey           = "dpi"
includePathKey   = "include"
saveFormatKey    = "format"
withLinksKey     = "links"
isTightBboxKey   = "tight_bbox"
isTransparentKey = "transparent"


-- | list of all keys related to pandoc-pyplot that
-- can be specified in source material.
inclusionKeys :: [Text]
inclusionKeys = [ directoryKey
                , captionKey
                , dpiKey
                , includePathKey
                , saveFormatKey
                , withLinksKey
                , isTightBboxKey
                , isTransparentKey
                ]


-- | Monad in which to run pandoc-pyplot computations
type PyplotM a = ReaderT Configuration IO a


-- | String representation of a Python script
type PythonScript = Text


-- | Rendering library
--
-- @since 2.2.0.0
data RenderingLibrary
    = Matplotlib -- ^ Rendering via the Matplotlib library. This library has the most features.
    | Plotly     -- ^ Rendering via the Plotly library.
    deriving (Show, Eq, Generic)

instance Hashable RenderingLibrary


-- | Possible result of running a Python script
data ScriptResult
    = ScriptSuccess
    | ScriptChecksFailed String
    | ScriptFailure Int


-- | Result of checking scripts for problems
data CheckResult
    = CheckPassed
    | CheckFailed String
    deriving (Eq)

instance Sem.Semigroup CheckResult where
    (<>) CheckPassed a                         = a
    (<>) a CheckPassed                         = a
    (<>) (CheckFailed msg1) (CheckFailed msg2) = CheckFailed (msg1 <> msg2)

instance Monoid CheckResult where
    mempty = CheckPassed

#if !(MIN_VERSION_base(4,11,0))
    mappend = (<>)
#endif


-- | Possible errors returned by the filter
data PandocPyplotError
    = ScriptError Int                 -- ^ Running Python script has yielded an error
    | ScriptChecksFailedError String  -- ^ Python script did not pass all checks
    deriving (Eq)

instance Show PandocPyplotError where
    show (ScriptError exitcode)        = "Script error: plot could not be generated. Exit code " <> (show exitcode)
    show (ScriptChecksFailedError msg) = "Script did not pass all checks: " <> msg


-- | Generated figure file format supported by pandoc-pyplot.
-- Note: all formats are supported by Matplotlib, but not all
-- formats are supported by Plotly
data SaveFormat
    = PNG
    | PDF
    | SVG
    | JPG
    | EPS
    | GIF
    | TIF
    deriving (Bounded, Enum, Eq, Show, Generic)

instance IsString SaveFormat where
    -- | An error is thrown if the save format cannot be parsed.
    fromString s
        | s `elem` ["png", "PNG", ".png"] = PNG
        | s `elem` ["pdf", "PDF", ".pdf"] = PDF
        | s `elem` ["svg", "SVG", ".svg"] = SVG
        | s `elem` ["eps", "EPS", ".eps"] = EPS
        | s `elem` ["gif", "GIF", ".gif"] = GIF
        | s `elem` ["jpg", "jpeg", "JPG", "JPEG", ".jpg", ".jpeg"] = JPG
        | s `elem` ["tif", "tiff", "TIF", "TIFF", ".tif", ".tiff"] = TIF
        | otherwise = error $ 
                mconcat [ s
                        , " is not one of valid save format : "
                        , mconcat $ intersperse ", " $ show <$> saveFormats
                        ]
        where
            saveFormats =  (enumFromTo minBound maxBound) :: [SaveFormat]

instance Hashable SaveFormat -- From Generic

-- | Save format file extension
extension :: SaveFormat -> String
extension fmt = mconcat [".", fmap toLower . show $ fmt]

-- | Default interpreter should be Python 3, which has a different
-- name on Windows ("python") vs Unix ("python3")
--
-- @since 2.1.2.0
defaultPlatformInterpreter :: String
#if defined(mingw32_HOST_OS)
defaultPlatformInterpreter = "python"
#else
defaultPlatformInterpreter = "python3"
#endif

-- | Configuration of pandoc-pyplot, describing the default behavior
-- of the filter.
--
-- A Configuration is useful when dealing with lots of figures; it avoids
-- repeating the same values.sta
--
-- @since 2.1.0.0
data Configuration
    = Configuration
        { defaultDirectory     :: FilePath     -- ^ The default directory where figures will be saved.
        , defaultIncludeScript :: PythonScript -- ^ The default script to run before other instructions.
        , defaultWithLinks     :: Bool         -- ^ The default behavior of whether or not to include links to source code and high-res
        , defaultSaveFormat    :: SaveFormat   -- ^ The default save format of generated figures.
        , defaultDPI           :: Int          -- ^ The default dots-per-inch value for generated figures. Matplotlib only, ignored otherwise.
        , isTightBbox          :: Bool         -- ^ Whether the figures should be saved with @bbox_inches="tight"@ or not. Useful for larger figures with subplots. Matplotlib only, ignored otherwise.
        , isTransparent        :: Bool         -- ^ If True, figures will be saved with transparent background rather than solid color. .Matplotlib only, ignored otherwise.
        , interpreter          :: String       -- ^ The name of the interpreter to use to render figures.
        , flags                :: [String]     -- ^ Command-line flags to be passed to the Python interpreger, e.g. ["-O", "-Wignore"]
        }
    deriving (Eq, Show)

instance Default Configuration where
    def = Configuration {
          defaultDirectory     = "generated/"
        , defaultIncludeScript = mempty
        , defaultWithLinks     = True
        , defaultSaveFormat    = PNG
        , defaultDPI           = 80
        , isTightBbox          = False
        , isTransparent        = False
        , interpreter          = defaultPlatformInterpreter
        , flags                = mempty
    }

instance ToJSON Configuration where
    toJSON (Configuration dir' _ withLinks' savefmt' dpi' tightbbox' transparent' interp' flags') =
        -- We ignore the include script as we want to examplify that
        -- this is for a filepath
            object [ directoryKey     .= dir'
                   , includePathKey   .= ("example.py" :: FilePath)
                   , withLinksKey     .= withLinks'
                   , dpiKey           .= dpi'
                   , saveFormatKey    .= (fmap toLower . show $ savefmt')
                   , isTightBboxKey   .= tightbbox'
                   , isTransparentKey .= transparent'
                   , "interpreter"    .= interp'
                   , "flags"          .= flags'
                   ]


-- | Datatype containing all parameters required to run pandoc-pyplot.
--
-- It is assumed that once a @FigureSpec@ has been created, no configuration
-- can overload it; hence, a @FigureSpec@ completely encodes a particular figure.
data FigureSpec = FigureSpec
    { caption      :: Text             -- ^ Figure caption.
    , withLinks    :: Bool             -- ^ Append links to source code and high-dpi figure to caption.
    , script       :: PythonScript     -- ^ Source code for the figure.
    , saveFormat   :: SaveFormat       -- ^ Save format of the figure.
    , directory    :: FilePath         -- ^ Directory where to save the file.
    , dpi          :: Int              -- ^ Dots-per-inch of figure.
    , renderingLib :: RenderingLibrary -- ^ Rendering library.
    , tightBbox    :: Bool             -- ^ Enforce tight bounding-box with @bbox_inches="tight"@.
    , transparent  :: Bool             -- ^ Make figure background transparent.
    , blockAttrs   :: Attr             -- ^ Attributes not related to @pandoc-pyplot@ will be propagated.
    } deriving Generic

instance Hashable FigureSpec -- From Generic