Debian Codegraph @

src/Diagrams/Backend/Cairo/CmdLine.hs

raw
1 {-# LANGUAGE CPP #-}
2 {-# LANGUAGE FlexibleInstances #-}
3 {-# LANGUAGE TemplateHaskell #-}
4 {-# LANGUAGE TypeFamilies #-}
5
6 {-# OPTIONS_GHC -fno-warn-orphans #-}
7
8 -----------------------------------------------------------------------------
9 -- |
10 -- Module : Diagrams.Backend.Cairo.CmdLine
11 -- Copyright : (c) 2013 Diagrams-cairo team (see LICENSE)
12 -- License : BSD-style (see LICENSE)
13 -- Maintainer : [email protected]
14 --
15 -- Convenient creation of command-line-driven executables for
16 -- rendering diagrams using the cairo backend.
17 --
18 -- * 'defaultMain' creates an executable which can render a single
19 -- diagram at various options.
20 --
21 -- * 'multiMain' is like 'defaultMain' but allows for a list of
22 -- diagrams from which the user can choose one to render.
23 --
24 -- * 'animMain' is like 'defaultMain' but for animations instead of
25 -- diagrams.
26 --
27 -- * `gifMain` creates an executable to generate an animated GIF.
28 --
29 -- * 'mainWith' is a generic form that does all of the above but with
30 -- a slightly scarier type. See "Diagrams.Backend.CmdLine". This
31 -- form can also take a function type that has a suitable final result
32 -- (any of arguments to the above types) and 'Parseable' arguments.
33 --
34 -- If you want to generate diagrams programmatically---/i.e./ if you
35 -- want to do anything more complex than what the below functions
36 -- provide---you have several options.
37 --
38 -- * Use a function with 'mainWith'. This may require making
39 -- 'Parseable' instances for custom argument types.
40 --
41 -- * Make a new 'Mainable' instance. This may require a newtype
42 -- wrapper on your diagram type to avoid the existing instances.
43 -- This gives you more control over argument parsing, intervening
44 -- steps, and diagram creation.
45 --
46 -- * Build option records and pass them along with a diagram to 'mainRender'
47 -- from "Diagrams.Backend.CmdLine".
48 --
49 -- * A more flexible approach is to use the 'renderCairo' function
50 -- provided in the "Diagrams.Backend.Cairo" module.
51 --
52 -- * For the most flexibility, you can call the generic 'renderDia'
53 -- function directly; see "Diagrams.Backend.Cairo" for more
54 -- information.
55 --
56 -- For a tutorial on command-line diagram creation see
57 -- <https://diagrams.github.io/doc/cmdline.html>.
58 --
59 -----------------------------------------------------------------------------
60
61 module Diagrams.Backend.Cairo.CmdLine
62 (
63 -- * General form of @main@
64 -- $mainwith
65
66 mainWith
67
68 -- * Supported forms of @main@
69
70 , defaultMain
71 , multiMain
72 , animMain
73 , gifMain
74
75 -- * GIF support
76
77 , GifOpts(..)
78 , gifRender
79
80 -- * Backend tokens
81
82 , Cairo
83 , B
84 ) where
85
86 import Codec.Picture
87 import Codec.Picture.ColorQuant (defaultPaletteOptions)
88 import qualified Data.ByteString.Lazy as L (ByteString, writeFile)
89 import Data.Vector.Storable (unsafeFromForeignPtr0)
90 import Data.Word (Word8)
91 import Options.Applicative
92
93 import Diagrams.Backend.Cairo
94 import Diagrams.Backend.Cairo.Ptr (renderForeignPtrOpaque)
95 import Diagrams.Backend.CmdLine
96 import Diagrams.Prelude hiding (height, interval,
97 option, output, width)
98
99 -- Below hack is needed because GHC 7.0.x has a bug regarding export
100 -- of data family constructors; see comments in Diagrams.Backend.Cairo
101 #if __GLASGOW_HASKELL__ < 702 || __GLASGOW_HASKELL__ >= 704
102 import Diagrams.Backend.Cairo.Internal
103 #endif
104
105 #if __GLASGOW_HASKELL__ < 710
106 import Foreign.ForeignPtr.Safe (ForeignPtr)
107 #else
108 import Foreign.ForeignPtr (ForeignPtr)
109 #endif
110
111 import Data.List.Split
112
113 -- | Extra options for animated GIFs.
114 data GifOpts = GifOpts { _dither :: Bool
115 , _noLooping :: Bool
116 , _loopRepeat :: Maybe Int}
117
118 makeLenses ''GifOpts
119
120
121 -- $mainwith
122 -- The 'mainWith' method unifies all of the other forms of @main@ and is now
123 -- the recommended way to build a command-line diagrams program. It works as a
124 -- direct replacement for 'defaultMain', 'multiMain', or 'animMain' as well as
125 -- allowing more general arguments. For example, given a function that
126 -- produces a diagram when given an @Int@ and a @'Colour' Double@, 'mainWith'
127 -- will produce a program that looks for additional number and color arguments.
128 --
129 -- > ... definitions ...
130 -- > f :: Int -> Colour Double -> Diagram Cairo
131 -- > f i c = ...
132 -- >
133 -- > main = mainWith f
134 --
135 -- We can run this program as follows:
136 --
137 -- > $ ghc --make MyDiagram
138 -- >
139 -- > # output image.png built by `f 20 red`
140 -- > $ ./MyDiagram -o image.png -w 200 20 red
141
142
143 -- | This is the simplest way to render diagrams, and is intended to
144 -- be used like so:
145 --
146 -- > ... other definitions ...
147 -- > myDiagram = ...
148 -- >
149 -- > main = defaultMain myDiagram
150 --
151 -- Compiling a source file like the above example will result in an
152 -- executable which takes command-line options for setting the size,
153 -- output file, and so on, and renders @myDiagram@ with the
154 -- specified options.
155 --
156 -- On Unix systems, the generated executable also supports a
157 -- rudimentary \"looped\" mode, which watches the source file for
158 -- changes and recompiles itself on the fly.
159 --
160 -- Pass @--help@ to the generated executable to see all available
161 -- options. Currently it looks something like
162 --
163 -- @
164 -- ./Program
165 --
166 -- Usage: ./Program [-w|--width WIDTH] [-h|--height HEIGHT] [-o|--output OUTPUT]
167 -- [--loop] [-s|--src ARG] [-i|--interval INTERVAL]
168 -- Command-line diagram generation.
169 --
170 -- Available options:
171 -- -?,--help Show this help text
172 -- -w,--width WIDTH Desired WIDTH of the output image
173 -- -h,--height HEIGHT Desired HEIGHT of the output image
174 -- -o,--output OUTPUT OUTPUT file
175 -- -l,--loop Run in a self-recompiling loop
176 -- -s,--src ARG Source file to watch
177 -- -i,--interval INTERVAL When running in a loop, check for changes every INTERVAL seconds.
178 -- @
179 --
180 -- For example, a couple common scenarios include
181 --
182 -- @
183 -- $ ghc --make MyDiagram
184 --
185 -- # output image.png with a width of 400px (and auto-determined height)
186 -- $ ./MyDiagram -o image.png -w 400
187 --
188 -- # output 200x200 dia.pdf, then watch for changes every 10 seconds
189 -- $ ./MyDiagram -o dia.pdf -h 200 -w 200 -l -i 10
190 -- @
191
192 defaultMain :: QDiagram Cairo V2 Double Any -> IO ()
193 defaultMain = mainWith
194
195 instance Mainable (QDiagram Cairo V2 Double Any) where
196 type MainOpts (QDiagram Cairo V2 Double Any) = DiagramOpts
197
198 mainRender opts d = chooseRender opts d
199
200 chooseRender :: DiagramOpts -> QDiagram Cairo V2 Double Any -> IO ()
201 chooseRender opts d =
202 case splitOn "." (opts ^. output) of
203 [""] -> putStrLn "No output file given."
204 ps | last ps `elem` ["png", "ps", "pdf", "svg"] -> do
205 let outTy = case last ps of
206 "png" -> PNG
207 "ps" -> PS
208 "pdf" -> PDF
209 "svg" -> SVG
210 _ -> PDF
211 fst $ renderDia
212 Cairo
213 ( CairoOptions
214 (opts^.output)
215 (fromIntegral <$> mkSizeSpec2D
216 (opts ^. width )
217 (opts ^. height)
218 )
219 outTy
220 False
221 )
222 d
223 | otherwise -> putStrLn $ "Unknown file type: " ++ last ps
224
225 -- | @multiMain@ is like 'defaultMain', except instead of a single
226 -- diagram it takes a list of diagrams paired with names as input.
227 -- The generated executable then takes a @--selection@ option
228 -- specifying the name of the diagram that should be rendered. The
229 -- list of available diagrams may also be printed by passing the
230 -- option @--list@.
231 --
232 -- Example usage:
233 --
234 -- @
235 -- $ ghc --make MultiTest
236 -- [1 of 1] Compiling Main ( MultiTest.hs, MultiTest.o )
237 -- Linking MultiTest ...
238 -- $ ./MultiTest --list
239 -- Available diagrams:
240 -- foo bar
241 -- $ ./MultiTest --selection bar -o Bar.png -w 200
242 -- @
243
244 multiMain :: [(String, QDiagram Cairo V2 Double Any)] -> IO ()
245 multiMain = mainWith
246
247 instance Mainable [(String, QDiagram Cairo V2 Double Any)] where
248 type MainOpts [(String, QDiagram Cairo V2 Double Any)]
249 = (MainOpts (QDiagram Cairo V2 Double Any), DiagramMultiOpts)
250
251 mainRender = defaultMultiMainRender
252
253 -- | @animMain@ is like 'defaultMain', but renders an animation
254 -- instead of a diagram. It takes as input an animation and produces
255 -- a command-line program which will crudely \"render\" the animation
256 -- by rendering one image for each frame, named by extending the given
257 -- output file name by consecutive integers. For example if the given
258 -- output file name is @foo\/blah.png@, the frames will be saved in
259 -- @foo\/blah001.png@, @foo\/blah002.png@, and so on (the number of
260 -- padding digits used depends on the total number of frames). It is
261 -- up to the user to take these images and stitch them together into
262 -- an actual animation format (using, /e.g./ @ffmpeg@).
263 --
264 -- Of course, this is a rather crude method of rendering animations;
265 -- more sophisticated methods will likely be added in the future.
266 --
267 -- The @--fpu@ option can be used to control how many frames will be
268 -- output for each second (unit time) of animation.
269 animMain :: Animation Cairo V2 Double -> IO ()
270 animMain = mainWith
271
272 instance Mainable (Animation Cairo V2 Double) where
273 type MainOpts (Animation Cairo V2 Double) = (DiagramOpts, DiagramAnimOpts)
274
275 mainRender opts d = defaultAnimMainRender chooseRender output opts d
276
277 -- | @gifMain@ takes a list of diagram and delay time pairs and produces a
278 -- command line program to generate an animated GIF, with options @GifOpts@.
279 -- "Delay times are in 1/100ths of a second."
280 --
281 -- Example usage:
282 --
283 -- @
284 -- $ ghc --make GifTest
285 -- [1 of 1] Compiling Main ( GifTest.hs, GifTest.o )
286 -- Linking GifTest ...
287 -- ./GifTest --help
288 -- GifTest
289 --
290 -- Usage: GifTest [-w|--width WIDTH] [-h|--height HEIGHT] [-o|--output OUTPUT]
291 -- [--dither] [--looping-off] [--loop-repeat ARG]
292 -- Command-line diagram generation.
293 --
294 -- Available options:
295 -- -?,--help Show this help text
296 -- -w,--width WIDTH Desired WIDTH of the output image
297 -- -h,--height HEIGHT Desired HEIGHT of the output image
298 -- -o,--output OUTPUT OUTPUT file
299 -- --dither Turn on dithering.
300 -- --looping-off Turn looping off
301 -- --loop-repeat ARG Number of times to repeat
302 -- @
303 gifMain :: [(QDiagram Cairo V2 Double Any, GifDelay)] -> IO ()
304 gifMain = mainWith
305
306 -- | Command line parser for 'GifOpts'.
307 -- @--dither@ turn dithering on.
308 -- @--looping-off@ turn looping off, i.e play GIF once.
309 -- @--loop-repeat@ number of times to repeat the GIF after the first playing.
310 -- this option is only used if @--looping-off@ is not set.
311 instance Parseable GifOpts where
312 parser = GifOpts <$> switch
313 ( long "dither"
314 <> help "Turn on dithering." )
315 <*> switch
316 ( long "looping-off"
317 <> help "Turn looping off" )
318 <*> ( optional . option auto )
319 ( long "loop-repeat"
320 <> help "Number of times to repeat" )
321
322 instance Mainable [(QDiagram Cairo V2 Double Any, GifDelay)] where
323 type MainOpts [(QDiagram Cairo V2 Double Any, GifDelay)] = (DiagramOpts, GifOpts)
324
325 mainRender (dOpts, gOpts) ds = gifRender (dOpts, gOpts) ds
326
327 imageRGB8FromUnsafePtr :: Int -> Int -> ForeignPtr Word8 -> Image PixelRGB8
328 imageRGB8FromUnsafePtr w h ptr = pixelMap f cImg
329 where
330 f (PixelRGBA8 b g r _) = PixelRGB8 r g b
331 cImg = Image w h $ unsafeFromForeignPtr0 ptr (w * h * 4)
332
333
334 encodeGifAnimation' :: [GifDelay] -> GifLooping -> Bool
335 -> [Image PixelRGB8] -> Either String L.ByteString
336 encodeGifAnimation' delays looping dithering lst =
337 encodeGifImages looping triples
338 where
339 triples = zipWith (\(x,z) y -> (x, y, z)) doubles delays
340 doubles = [(pal, img)
341 | (img, pal) <- palettize
342 defaultPaletteOptions {enableImageDithering=dithering} <$> lst]
343
344 writeGifAnimation' :: FilePath -> [GifDelay] -> GifLooping -> Bool
345 -> [Image PixelRGB8] -> Either String (IO ())
346 writeGifAnimation' path delays looping dithering img =
347 L.writeFile path <$> encodeGifAnimation' delays looping dithering img
348
349 scaleInt :: Int -> Double -> Double -> Int
350 scaleInt i num denom
351 | num == 0 || denom == 0 = i
352 | otherwise = round (num / denom * fromIntegral i)
353
354 gifRender :: (DiagramOpts, GifOpts) -> [(QDiagram Cairo V2 Double Any, GifDelay)] -> IO ()
355 gifRender (dOpts, gOpts) lst =
356 case splitOn "." (dOpts^.output) of
357 [""] -> putStrLn "No output file given"
358 ps | last ps == "gif" -> do
359 let (w, h) = case (dOpts^.width, dOpts^.height) of
360 (Just w', Just h') -> (w', h')
361 (Just w', Nothing) -> (w', scaleInt w' diaHeight diaWidth)
362 (Nothing, Just h') -> (scaleInt h' diaWidth diaHeight, h')
363 (Nothing, Nothing) -> (100, 100)
364 looping = if gOpts^.noLooping
365 then LoopingNever
366 else case gOpts^.loopRepeat of
367 Nothing -> LoopingForever
368 Just n -> LoopingRepeat (fromIntegral n)
369 dias = map fst lst
370 delays = map snd lst
371 V2 diaWidth diaHeight = size (head dias)
372 fPtrs <- mapM (renderForeignPtrOpaque w h) dias
373 let imageRGB8s = map (imageRGB8FromUnsafePtr w h) fPtrs
374 result = writeGifAnimation'
375 (dOpts^.output)
376 delays
377 looping
378 (gOpts^.dither)
379 imageRGB8s
380 case result of
381 Left s -> putStrLn s
382 Right io -> io
383 | otherwise -> putStrLn "File name must end with .gif"