Debian Codegraph @

src/Diagrams/Backend/CmdLine.hs

raw symbols SCIP
1 {-# LANGUAGE CPP #-}
2 {-# LANGUAGE ConstrainedClassMethods #-}
3 {-# LANGUAGE DeriveDataTypeable #-}
4 {-# LANGUAGE FlexibleContexts #-}
5 {-# LANGUAGE FlexibleInstances #-}
6 {-# LANGUAGE NoMonomorphismRestriction #-}
7 {-# LANGUAGE RankNTypes #-}
8 {-# LANGUAGE TemplateHaskell #-}
9 {-# LANGUAGE TypeFamilies #-}
10 {-# LANGUAGE UndecidableInstances #-}
11 -----------------------------------------------------------------------------
12 -- |
13 -- Module : Diagrams.Backend.CmdLine
14 -- Copyright : (c) 2013 Diagrams team (see LICENSE)
15 -- License : BSD-style (see LICENSE)
16 -- Maintainer : [email protected]
17 --
18 -- Convenient creation of command-line-driven executables for rendering
19 -- diagrams. This module provides a general framework and default
20 -- behaviors for parsing command-line arguments, records for diagram
21 -- creation options in various forms, and classes and instances for a
22 -- unified entry point to command-line-driven diagram creation
23 -- executables.
24 --
25 -- For a tutorial on command-line diagram creation see
26 -- <https://diagrams.github.io/doc/cmdline.html>.
27 --
28 -----------------------------------------------------------------------------
29
30 module Diagrams.Backend.CmdLine
31 (
32
33 -- * Options
34
35 -- ** Standard options
36 DiagramOpts(..)
37 , diagramOpts
38 , width
39 , height
40 , output
41
42 -- ** Multi-diagram options
43 , DiagramMultiOpts(..)
44 , diagramMultiOpts
45 , selection
46 , list
47
48 -- ** Animation options
49 , DiagramAnimOpts(..)
50 , diagramAnimOpts
51 , fpu
52
53 -- * Parsing
54 , Parseable(..)
55 , readHexColor
56
57 -- * Command-line programs (@Mainable@)
58 -- ** Arguments, rendering, and entry point
59 , Mainable(..)
60
61 -- ** General currying
62 , ToResult(..)
63
64 -- ** helper functions for implementing @mainRender@
65 , defaultAnimMainRender
66 , defaultMultiMainRender
67 ) where
68
69 import Control.Lens (Lens', makeLenses, (&), (.~), (^.))
70 import Diagrams.Animation
71 import Diagrams.Attributes
72 import Diagrams.Core hiding (output)
73
74 import Options.Applicative
75 import Options.Applicative.Types (readerAsk)
76
77 import Control.Monad (forM_)
78
79 -- MonadFail comes from Prelude in base-4.13 and up
80 #if !MIN_VERSION_base(4,13,0)
81 import Control.Monad.Fail (MonadFail)
82 #endif
83
84 import Data.Active hiding (interval)
85 import Data.Char (isDigit)
86 import Data.Colour
87 import Data.Colour.Names
88 import Data.Colour.SRGB
89 import Data.Data
90 import Data.Functor.Identity
91 import Data.Kind (Type)
92 import Data.Monoid
93 import Numeric
94
95 import System.Environment (getProgName)
96 import System.FilePath (addExtension, splitExtension)
97
98 import Text.Printf
99
100 -- | Standard options most diagrams are likely to have.
101 data DiagramOpts = DiagramOpts
102 { _width :: Maybe Int -- ^ Final output width of diagram.
103 , _height :: Maybe Int -- ^ Final output height of diagram.
104 , _output :: FilePath -- ^ Output file path, format is typically chosen by extension.
105 }
106 deriving (Show, Data, Typeable)
107
108 makeLenses ''DiagramOpts
109
110 -- | Extra options for a program that can offer a choice
111 -- between multiple diagrams.
112 data DiagramMultiOpts = DiagramMultiOpts
113 { _selection :: Maybe String -- ^ Selected diagram to render.
114 , _list :: Bool -- ^ Flag to indicate that a list of available diagrams should
115 -- be printed to standard out.
116 }
117 deriving (Show, Data, Typeable)
118
119 makeLenses ''DiagramMultiOpts
120
121 -- | Extra options for animations.
122 data DiagramAnimOpts = DiagramAnimOpts
123 { _fpu :: Double -- ^ Number of frames per unit time to generate for the animation.
124 }
125 deriving (Show, Data, Typeable)
126
127 makeLenses ''DiagramAnimOpts
128
129 -- | Command line parser for 'DiagramOpts'.
130 -- Width is option @--width@ or @-w@.
131 -- Height is option @--height@ or @-h@ (note we change help to be @-?@ due to this).
132 -- Output is option @--output@ or @-o@.
133 diagramOpts :: Parser DiagramOpts
134 diagramOpts = DiagramOpts
135 <$> (optional . option auto)
136 ( long "width" <> short 'w'
137 <> metavar "WIDTH"
138 <> help "Desired WIDTH of the output image")
139 <*> (optional . option auto)
140 ( long "height" <> short 'h'
141 <> metavar "HEIGHT"
142 <> help "Desired HEIGHT of the output image")
143 <*> strOption
144 ( long "output" <> short 'o'
145 <> value ""
146 <> metavar "OUTPUT"
147 <> help "OUTPUT file")
148
149 -- | Command line parser for 'DiagramMultiOpts'.
150 -- Selection is option @--selection@ or @-S@.
151 -- List is @--list@ or @-L@.
152 diagramMultiOpts :: Parser DiagramMultiOpts
153 diagramMultiOpts = DiagramMultiOpts
154 <$> (optional . strOption)
155 ( long "selection" <> short 'S'
156 <> metavar "NAME"
157 <> help "NAME of the diagram to render")
158 <*> switch
159 ( long "list" <> short 'L'
160 <> help "List all available diagrams")
161
162 -- | Command line parser for 'DiagramAnimOpts'
163 -- Frames per unit is @--fpu@ or @-f@.
164 diagramAnimOpts :: Parser DiagramAnimOpts
165 diagramAnimOpts = DiagramAnimOpts
166 <$> option auto
167 ( long "fpu" <> short 'f'
168 <> value 30.0
169 <> help "Frames per unit time (for animations)")
170
171 -- | A hidden \"helper\" option which always fails.
172 -- Taken from Options.Applicative.Extra but without the
173 -- short option 'h'. We want the 'h' for Height.
174 helper' :: Parser (a -> a)
175 helper' = abortOption param $ mconcat
176 [ long "help"
177 , short '?'
178 , help "Show this help text"
179 ]
180 where
181 #if MIN_VERSION_optparse_applicative(0,16,0)
182 param = ShowHelpText Nothing
183 #else
184 param = ShowHelpText
185 #endif
186
187 -- | Apply a parser to the command line that includes the standard
188 -- program description and help behavior. Results in parsed commands
189 -- or fails with a help message.
190 defaultOpts :: Parser a -> IO a
191 defaultOpts optsParser = do
192 prog <- getProgName
193 let p = info (helper' <*> optsParser)
194 ( fullDesc
195 <> progDesc "Command-line diagram generation."
196 <> header prog)
197 execParser p
198
199 -- | Parseable instances give a command line parser for a type. If a custom
200 -- parser for a common type is wanted a newtype wrapper could be used to make
201 -- a new 'Parseable' instance. Notice that we do /not/ want as many
202 -- instances as 'Read' because we want to limit ourselves to things that make
203 -- sense to parse from the command line.
204 class Parseable a where
205 parser :: Parser a
206
207 -- The following instance would overlap with the product instance for
208 -- Parseable. We can't tell if one wants to parse (a,b) as one argument or a
209 -- as one argument and b as another. Since this is the command line we almost
210 -- certainly want the latter. So we need to have less Read instances.
211 --
212 -- instance Read a => Parseable a where
213 -- parser = argument auto mempty
214
215 -- | Parse 'Int' according to its 'Read' instance.
216 instance Parseable Int where
217 parser = argument auto mempty
218
219 -- | Parse 'Double' according to its 'Read' instance.
220 instance Parseable Double where
221 parser = argument auto mempty
222
223 -- | Parse a string by just accepting the given string.
224 instance Parseable String where
225 parser = argument str mempty
226
227 -- | Parse 'DiagramOpts' using the 'diagramOpts' parser.
228 instance Parseable DiagramOpts where
229 parser = diagramOpts
230
231 -- | Parse 'DiagramMultiOpts' using the 'diagramMultiOpts' parser.
232 instance Parseable DiagramMultiOpts where
233 parser = diagramMultiOpts
234
235 -- | Parse 'DiagramAnimOpts' using the 'diagramAnimOpts' parser.
236 instance Parseable DiagramAnimOpts where
237 parser = diagramAnimOpts
238
239 -- | Parse @'Colour' Double@ as either a named color from "Data.Colour.Names"
240 -- or a hexadecimal color.
241 instance Parseable (Colour Double) where
242 parser = argument (rc <|> rh) mempty
243 where
244 rh, rc :: ReadM (Colour Double)
245 rh = f . colorToSRGBA <$> (readerAsk >>= readHexColor)
246 rc = readerAsk >>= readColourName
247 f (r,g,b,_) = sRGB r g b -- TODO: this seems unfortunate. Should the alpha
248 -- value be applied to the r g b values?
249
250 -- | Parse @'AlphaColour' Double@ as either a named color from "Data.Colour.Names"
251 -- or a hexadecimal color.
252 instance Parseable (AlphaColour Double) where
253 parser = argument (rc <|> rh) mempty
254 where
255 rh = readerAsk >>= readHexColor
256 rc = opaque <$> (readerAsk >>= readColourName)
257
258 -- Addapted from the Clay.Color module of the clay package
259
260 -- | Parses a hexadecimal color. The string can start with @\"0x\"@ or @\"#\"@
261 -- or just be a string of hexadecimal values. If four or three digits are
262 -- given each digit is repeated to form a full 24 or 32 bit color. For
263 -- example, @\"0xfc4\"@ is the same as @\"0xffcc44\"@. When eight or six
264 -- digits are given each pair of digits is a color or alpha channel with the
265 -- order being red, green, blue, alpha.
266 readHexColor :: (Applicative m, MonadFail m) => String -> m (AlphaColour Double)
267 readHexColor cs = case cs of
268 ('0':'x':hs) -> handle hs
269 ('#':hs) -> handle hs
270 hs -> handle hs
271 where
272 handle hs | length hs <= 8 && all isHexDigit hs
273 = case hs of
274 [a,b,c,d,e,f,g,h] -> withOpacity <$> (sRGB <$> hex a b <*> hex c d <*> hex e f) <*> hex g h
275 [a,b,c,d,e,f ] -> opaque <$> (sRGB <$> hex a b <*> hex c d <*> hex e f)
276 [a,b,c,d ] -> withOpacity <$> (sRGB <$> hex a a <*> hex b b <*> hex c c) <*> hex d d
277 [a,b,c ] -> opaque <$> (sRGB <$> hex a a <*> hex b b <*> hex c c)
278 _ -> fail $ "could not parse as a colour" ++ cs
279 handle _ = fail $ "could not parse as a colour: " ++ cs
280
281 isHexDigit c = isDigit c || c `elem` "abcdef"
282
283 hex a b = (/ 255) <$> case readHex [a,b] of
284 [(h,"")] -> return h
285 _ -> fail $ "could not parse as a hex value" ++ [a,b]
286
287
288 -- | This instance is needed to signal the end of a chain of
289 -- nested tuples, it always just results in the unit value
290 -- without consuming anything.
291 instance Parseable () where
292 parser = pure ()
293
294 -- | Allow 'Parseable' things to be combined.
295 instance (Parseable a, Parseable b) => Parseable (a,b) where
296 parser = (,) <$> parser <*> parser
297
298 -- | Triples of Parsebales should also be Parseable.
299 instance (Parseable a, Parseable b, Parseable c) => Parseable (a, b, c) where
300 parser = (,,) <$> parser <*> parser <*> parser
301
302 instance (Parseable a, Parseable b, Parseable c, Parseable d) => Parseable (a, b, c, d) where
303 parser = (,,,) <$> parser <*> parser <*> parser <*> parser
304
305 -- | This class allows us to abstract over functions that take some arguments
306 -- and produce a final value. When some @d@ is an instance of
307 -- 'ToResult' we get a type @'Args' d@ that is a type of /all/ the arguments
308 -- at once, and a type @'ResultOf' d@ that is the type of the final result from
309 -- some base case instance.
310 class ToResult d where
311 type Args d :: Type
312 type ResultOf d :: Type
313
314 toResult :: d -> Args d -> ResultOf d
315
316 -- | A diagram can always produce a diagram when given @()@ as an argument.
317 -- This is our base case.
318 instance ToResult (QDiagram b v n Any) where
319 type Args (QDiagram b v n Any) = ()
320 type ResultOf (QDiagram b v n Any) = QDiagram b v n Any
321
322 toResult d _ = d
323
324 -- | A list of diagrams can produce pages.
325 instance ToResult [QDiagram b v n Any] where
326 type Args [QDiagram b v n Any] = ()
327 type ResultOf [QDiagram b v n Any] = [QDiagram b v n Any]
328
329 toResult ds _ = ds
330
331 -- | A list of named diagrams can give the multi-diagram interface.
332 instance ToResult [(String, QDiagram b v n Any)] where
333 type Args [(String,QDiagram b v n Any)] = ()
334 type ResultOf [(String,QDiagram b v n Any)] = [(String,QDiagram b v n Any)]
335
336 toResult ds _ = ds
337
338 -- | An animation is another suitable base case.
339 instance ToResult (Animation b v n) where
340 type Args (Animation b v n) = ()
341 type ResultOf (Animation b v n) = Animation b v n
342
343 toResult a _ = a
344
345 -- | Diagrams that require IO to build are a base case.
346 instance ToResult d => ToResult (IO d) where
347 type Args (IO d) = Args d
348 type ResultOf (IO d) = IO (ResultOf d)
349
350 toResult d args = flip toResult args <$> d
351
352 -- | An instance for a function that, given some 'a', can produce a 'd' that is
353 -- also an instance of 'ToResult'. For this to work we need both the
354 -- argument 'a' and all the arguments that 'd' will need. Producing the
355 -- result is simply applying the argument to the producer and passing the
356 -- remaining arguments to the produced producer.
357
358 -- The previous paragraph stands as a witness to the fact that Haskell code
359 -- is clearer and easier to understand then paragraphs in English written by
360 -- me.
361 instance ToResult d => ToResult (a -> d) where
362 type Args (a -> d) = (a, Args d)
363 type ResultOf (a -> d) = ResultOf d
364
365 toResult f (a,args) = toResult (f a) args
366
367
368 -- | This class represents the various ways we want to support diagram creation
369 -- from the command line. It has the right instances to select between creating
370 -- single static diagrams, multiple static diagrams, static animations, and
371 -- functions that produce diagrams as long as the arguments are 'Parseable'.
372 --
373 -- Backends are expected to create @Mainable@ instances for the types that are
374 -- suitable for generating output in the backend's format. For instance,
375 -- Postscript can handle single diagrams, pages of diagrams, animations as
376 -- separate files, and association lists. This implies instances for
377 -- @Diagram Postscript R2@, @[Diagram Postscript R2]@, @Animation Postscript R2@,
378 -- and @[(String,Diagram Postscript R2)]@. We can consider these as the base
379 -- cases for the function instance.
380 --
381 -- The associated type 'MainOpts' describes the options which need to be parsed
382 -- from the command-line and passed to @mainRender@.
383 class Mainable d where
384 -- | Associated type that describes the options which need to be parsed
385 -- from the command-line and passed to @mainRender@.
386 type MainOpts d :: Type
387
388 -- | This method invokes the command-line parser resulting in an options
389 -- value or ending the program with an error or help message.
390 -- Typically the default instance will work. If a different help message
391 -- or parsing behavior is desired a new implementation is appropriate.
392 mainArgs :: Parseable (MainOpts d) => proxy d -> IO (MainOpts d)
393 mainArgs _ = defaultOpts parser
394
395 -- | Backend specific work of rendering with the given options and mainable
396 -- value is done here. All backend instances should implement this method.
397 mainRender :: MainOpts d -> d -> IO ()
398
399 -- | Main entry point for command-line diagram creation. This is the method
400 -- that users will call from their program @main@. For instance an expected
401 -- user program would take the following form.
402 --
403 -- @
404 -- import Diagrams.Prelude
405 -- import Diagrams.Backend.TheBestBackend.CmdLine
406 --
407 -- d :: Diagram B R2
408 -- d = ...
409 --
410 -- main = mainWith d
411 -- @
412 --
413 -- Most backends should be able to use the default implementation. A different
414 -- implementation should be used to handle more complex interactions with the user.
415 mainWith :: Parseable (MainOpts d) => d -> IO ()
416 mainWith d = do
417 opts <- mainArgs (Identity d)
418 mainRender opts d
419
420 -- | This instance allows functions resulting in something that is 'Mainable' to
421 -- be 'Mainable'. It takes a parse of collected arguments and applies them to
422 -- the given function producing the 'Mainable' result.
423 instance (ToResult d, Mainable (ResultOf d))
424 => Mainable (a -> d) where
425 type MainOpts (a -> d) = (MainOpts (ResultOf (a -> d)), Args (a -> d))
426
427 mainRender (opts, a) f = mainRender opts (toResult f a)
428 -- TODO: why can't we get away with: instance (Parseable (Args (a -> d)), Mainable (ResultOf d)) => ...
429 -- Doesn't `Args (a -> d)` imply `ToResult (a -> d)` which implies `ToResult d` ?
430
431 -- | With this instance we can perform IO to produce something
432 -- 'Mainable' before rendering.
433 instance Mainable d => Mainable (IO d) where
434 type MainOpts (IO d) = MainOpts d
435
436 mainRender opts dio = dio >>= mainRender opts
437
438 -- | @defaultMultiMainRender@ is an implementation of 'mainRender' where
439 -- instead of a single diagram it takes a list of diagrams paired with names
440 -- as input. The generated executable then takes a @--selection@ option
441 -- specifying the name of the diagram that should be rendered. The list of
442 -- available diagrams may also be printed by passing the option @--list@.
443 --
444 -- Typically a backend can write its @[(String,QDiagram b v n Any)]@ instance as
445 --
446 -- @
447 -- instance Mainable [(String,QDiagram b v n Any)] where
448 -- type MainOpts [(String,QDiagram b v n Any)] = (DiagramOpts, DiagramMultiOpts)
449 -- mainRender = defaultMultiMainRender
450 -- @
451 --
452 -- We do not provide this instance in general so that backends can choose to
453 -- opt-in to this form or provide a different instance that makes more sense.
454 defaultMultiMainRender :: Mainable d => (MainOpts d, DiagramMultiOpts) -> [(String, d)] -> IO ()
455 defaultMultiMainRender (opts,multi) ds =
456 if multi^.list
457 then showDiaList (map fst ds)
458 else case multi^.selection of
459 Nothing -> putStrLn "No diagram selected." >> showDiaList (map fst ds)
460 Just sel -> case lookup sel ds of
461 Nothing -> putStrLn $ "Unknown diagram: " ++ sel
462 Just d -> mainRender opts d
463
464 -- | Display the list of diagrams available for rendering.
465 showDiaList :: [String] -> IO ()
466 showDiaList ds = do
467 putStrLn "Available diagrams:"
468 putStrLn $ " " ++ unwords ds
469
470 -- | @defaultAnimMainRender@ is an implementation of 'mainRender' which renders
471 -- an animation as numbered frames, named by extending the given output file
472 -- name by consecutive integers. For example if the given output file name is
473 -- @foo\/blah.ext@, the frames will be saved in @foo\/blah001.ext@,
474 -- @foo\/blah002.ext@, and so on (the number of padding digits used depends on
475 -- the total number of frames). It is up to the user to take these images and
476 -- stitch them together into an actual animation format (using, /e.g./
477 -- @ffmpeg@).
478 --
479 -- Of course, this is a rather crude method of rendering animations;
480 -- more sophisticated methods will likely be added in the future.
481 --
482 -- The @fpu@ option from 'DiagramAnimOpts' can be used to control how many frames will
483 -- be output for each second (unit time) of animation.
484 --
485 -- This function requires a lens into the structure that the particular backend
486 -- uses for its diagram base case. If @MainOpts (QDiagram b v n Any) ~ DiagramOpts@
487 -- then this lens will simply be 'output'. This lens is required because the
488 -- implementation works by modifying the output field and running the base @mainRender@.
489 -- Typically a backend can write its @Animation B V@ instance as
490 --
491 -- @
492 -- instance Mainable (Animation B V) where
493 -- type MainOpts (Animation B V) = (DiagramOpts, DiagramAnimOpts)
494 -- mainRender = defaultAnimMainRender output
495 -- @
496 --
497 -- We do not provide this instance in general so that backends can choose to
498 -- opt-in to this form or provide a different instance that makes more sense.
499
500 defaultAnimMainRender ::
501 (opts -> QDiagram b v n Any -> IO ())
502 -> Lens' opts FilePath -- ^ A lens into the output path.
503 -> (opts, DiagramAnimOpts)
504 -> Animation b v n
505 -> IO ()
506 defaultAnimMainRender renderF out (opts,animOpts) anim = do
507 let frames = simulate (toRational $ animOpts^.fpu) anim
508 nDigits = length . show . length $ frames
509 forM_ (zip [1..] frames) $ \(i,d) -> renderF (indexize out nDigits i opts) d
510
511 -- | @indexize d n@ adds the integer index @n@ to the end of the
512 -- output file name, padding with zeros if necessary so that it uses
513 -- at least @d@ digits.
514 indexize :: Lens' s FilePath -> Int -> Integer -> s -> s
515 indexize out nDigits i opts = opts & out .~ output'
516 where fmt = "%0" ++ show nDigits ++ "d"
517 output' = addExtension (base ++ printf fmt i) ext
518 (base, ext) = splitExtension (opts^.out)