Debian Codegraph @

src/Diagrams/Backend/Cairo/Internal.hs

raw
1 {-# LANGUAGE CPP #-}
2 {-# LANGUAGE DeriveDataTypeable #-}
3 {-# LANGUAGE DeriveGeneric #-}
4 {-# LANGUAGE ExistentialQuantification #-}
5 {-# LANGUAGE FlexibleContexts #-}
6 {-# LANGUAGE FlexibleInstances #-}
7 {-# LANGUAGE GADTs #-}
8 {-# LANGUAGE MultiParamTypeClasses #-}
9 {-# LANGUAGE ScopedTypeVariables #-}
10 {-# LANGUAGE TemplateHaskell #-}
11 {-# LANGUAGE TypeFamilies #-}
12 {-# LANGUAGE TypeOperators #-}
13 {-# LANGUAGE TypeSynonymInstances #-}
14 {-# LANGUAGE ViewPatterns #-}
15
16 -----------------------------------------------------------------------------
17 -- |
18 -- Module : Diagrams.Backend.Cairo.Internal
19 -- Copyright : (c) 2011 Diagrams-cairo team (see LICENSE)
20 -- License : BSD-style (see LICENSE)
21 -- Maintainer : [email protected]
22 --
23 -- This module contains the internal implementation guts of the
24 -- diagrams cairo backend. If you want to see how the cairo backend
25 -- works under the hood, you are in the right place (try clicking on
26 -- the \"Source\" links). (Guts under the hood, what an awful mixed
27 -- metaphor.) If you know what you are doing and really want access
28 -- to the internals of the implementation, you are also in the right
29 -- place. Otherwise, you should have no need of this module; import
30 -- "Diagrams.Backend.Cairo.CmdLine" or "Diagrams.Backend.Cairo"
31 -- instead.
32 --
33 -- The one exception is that this module may have to be imported
34 -- sometimes to work around an apparent bug in certain versions of
35 -- GHC, which results in a \"not in scope\" error for 'CairoOptions'.
36 --
37 -- The types of all the @fromX@ functions look funny in the Haddock
38 -- output, which displays them like @Type -> Type@. In fact they are
39 -- all of the form @Type -> Graphics.Rendering.Cairo.Type@, /i.e./
40 -- they convert from a diagrams type to a cairo type of the same name.
41 -----------------------------------------------------------------------------
42 module Diagrams.Backend.Cairo.Internal where
43
44 import Diagrams.Core.Compile
45 import Diagrams.Core.Transform
46
47 import Diagrams.Prelude hiding (font, opacity, view)
48 import Diagrams.TwoD.Adjust (adjustDia2D,
49 setDefault2DAttributes)
50 import Diagrams.TwoD.Path (Clip (Clip), getFillRule)
51 import Diagrams.TwoD.Text hiding (font)
52
53 import qualified Graphics.Rendering.Cairo as C
54 import qualified Graphics.Rendering.Cairo.Matrix as CM
55 import qualified Graphics.Rendering.Pango as P
56
57 import Codec.Picture
58 import Codec.Picture.Types (convertImage, packPixel,
59 promoteImage)
60
61
62 import Control.Exception (try)
63 import Control.Monad (when)
64 import Control.Monad.IO.Class
65 import qualified Control.Monad.StateStack as SS
66 import Control.Monad.Trans (lift)
67 import qualified Data.Array.MArray as MA
68 import Data.Bits (rotateL, (.&.))
69 import qualified Data.Foldable as F
70 import Data.Hashable (Hashable (..))
71 import Data.List (isSuffixOf)
72 import Data.Maybe (catMaybes, fromMaybe, isJust)
73 import Data.Tree
74 import Data.Typeable
75 import Data.Word (Word32)
76 import GHC.Generics (Generic)
77
78 -- | This data declaration is simply used as a token to distinguish
79 -- the cairo backend: (1) when calling functions where the type
80 -- inference engine would otherwise have no way to know which
81 -- backend you wanted to use, and (2) as an argument to the
82 -- 'Backend' and 'Renderable' type classes.
83 data Cairo = Cairo
84 deriving (Eq,Ord,Read,Show,Typeable)
85
86 type B = Cairo
87
88 type instance V Cairo = V2
89 type instance N Cairo = Double
90
91 -- | Output types supported by cairo, including four different file
92 -- types (PNG, PS, PDF, SVG). If you want to output directly to GTK
93 -- windows, see the @diagrams-gtk@ package.
94 data OutputType =
95 PNG -- ^ Portable Network Graphics output.
96 | PS -- ^ PostScript output
97 | PDF -- ^ Portable Document Format output.
98 | SVG -- ^ Scalable Vector Graphics output.
99 | RenderOnly -- ^ Don't output any file; the returned @IO ()@
100 -- action will do nothing, but the @Render ()@
101 -- action can be used (/e.g./ to draw to a Gtk
102 -- window; see the @diagrams-gtk@ package).
103 deriving (Eq, Ord, Read, Show, Bounded, Enum, Typeable, Generic)
104
105 instance Hashable OutputType
106
107 -- | Custom state tracked in the 'RenderM' monad.
108 data CairoState
109 = CairoState { _accumStyle :: Style V2 Double
110 -- ^ The current accumulated style.
111 , _ignoreFill :: Bool
112 -- ^ Whether or not we saw any lines in the most
113 -- recent path (as opposed to loops). If we did,
114 -- we should ignore any fill attribute.
115 -- diagrams-lib separates lines and loops into
116 -- separate path primitives so we don't have to
117 -- worry about seeing them together in the same
118 -- path.
119 }
120
121 $(makeLenses ''CairoState)
122
123 instance Default CairoState where
124 def = CairoState
125 { _accumStyle = mempty
126 , _ignoreFill = False
127 }
128
129 -- | The custom monad in which intermediate drawing options take
130 -- place; 'Graphics.Rendering.Cairo.Render' is cairo's own rendering
131 -- monad.
132 type RenderM a = SS.StateStackT CairoState C.Render a
133
134 liftC :: C.Render a -> RenderM a
135 liftC = lift
136
137 runRenderM :: RenderM a -> C.Render a
138 runRenderM = flip SS.evalStateStackT def
139
140 -- | Push the current context onto a stack.
141 save :: RenderM ()
142 save = SS.save >> liftC C.save
143
144 -- | Restore the context from a stack.
145 restore :: RenderM ()
146 restore = liftC C.restore >> SS.restore
147
148 instance Backend Cairo V2 Double where
149 data Render Cairo V2 Double = C (RenderM ())
150 type Result Cairo V2 Double = (IO (), C.Render ())
151 data Options Cairo V2 Double = CairoOptions
152 { _cairoFileName :: String -- ^ The name of the file you want generated
153 , _cairoSizeSpec :: SizeSpec V2 Double -- ^ The requested size of the output
154 , _cairoOutputType :: OutputType -- ^ the output format and associated options
155 , _cairoBypassAdjust :: Bool -- ^ Should the 'adjustDia' step be bypassed during rendering?
156 }
157 deriving (Show, Eq)
158
159 renderRTree _ opts t = (renderIO, r)
160 where
161 r = runRenderM .runC . toRender $ t
162 renderIO = do
163 let surfaceF s = C.renderWith s r
164 V2 w h = specToSize 1 (opts^.cairoSizeSpec)
165 case opts^.cairoOutputType of
166 PNG ->
167 C.withImageSurface C.FormatARGB32 (round w) (round h) $ \surface -> do
168 surfaceF surface
169 C.surfaceWriteToPNG surface (opts^.cairoFileName)
170 PS -> C.withPSSurface (opts^.cairoFileName) w h surfaceF
171 PDF -> C.withPDFSurface (opts^.cairoFileName) w h surfaceF
172 SVG -> C.withSVGSurface (opts^.cairoFileName) w h surfaceF
173 RenderOnly -> return ()
174
175 adjustDia c opts d = if _cairoBypassAdjust opts
176 then (opts, mempty, d # setDefault2DAttributes)
177 else let (opts', transformation, d') = adjustDia2D cairoSizeSpec c opts (d # reflectY)
178 in (opts', transformation <> reflectionY, d')
179
180 runC :: Render Cairo V2 Double -> RenderM ()
181 runC (C r) = r
182
183 instance Semigroup (Render Cairo V2 Double) where
184 C rd1 <> C rd2 = C (rd1 >> rd2)
185
186 instance Monoid (Render Cairo V2 Double) where
187 mempty = C $ return ()
188 #if !(MIN_VERSION_base(4,11,0))
189 mappend = (<>)
190 #endif
191
192 instance Hashable (Options Cairo V2 Double) where
193 hashWithSalt s (CairoOptions fn sz out adj)
194 = s `hashWithSalt`
195 fn `hashWithSalt`
196 sz `hashWithSalt`
197 out `hashWithSalt`
198 adj
199
200 toRender :: RTree Cairo V2 Double a -> Render Cairo V2 Double
201 toRender (Node (RPrim p) _) = render Cairo p
202 toRender (Node (RStyle sty) rs) = C $ do
203 save
204 cairoStyle sty
205 accumStyle %= (<> sty)
206 runC $ F.foldMap toRender rs
207 restore
208 toRender (Node _ rs) = F.foldMap toRender rs
209
210 cairoFileName :: Lens' (Options Cairo V2 Double) String
211 cairoFileName = lens (\(CairoOptions {_cairoFileName = f}) -> f)
212 (\o f -> o {_cairoFileName = f})
213
214 cairoSizeSpec :: Lens' (Options Cairo V2 Double) (SizeSpec V2 Double)
215 cairoSizeSpec = lens (\(CairoOptions {_cairoSizeSpec = s}) -> s)
216 (\o s -> o {_cairoSizeSpec = s})
217
218 cairoOutputType :: Lens' (Options Cairo V2 Double) OutputType
219 cairoOutputType = lens (\(CairoOptions {_cairoOutputType = t}) -> t)
220 (\o t -> o {_cairoOutputType = t})
221
222 cairoBypassAdjust :: Lens' (Options Cairo V2 Double) Bool
223 cairoBypassAdjust = lens (\(CairoOptions {_cairoBypassAdjust = b}) -> b)
224 (\o b -> o {_cairoBypassAdjust = b})
225
226 -- | Render an object that the cairo backend knows how to render.
227 renderC :: (Renderable a Cairo, V a ~ V2, N a ~ Double) => a -> RenderM ()
228 renderC = runC . render Cairo
229
230 -- | Get an accumulated style attribute from the render monad state.
231 getStyleAttrib :: AttributeClass a => (a -> b) -> RenderM (Maybe b)
232 getStyleAttrib f = (fmap f . getAttr) <$> use accumStyle
233
234 -- | Handle those style attributes for which we can immediately emit
235 -- cairo instructions as we encounter them in the tree (clip, font
236 -- size, fill rule, line width, cap, join, and dashing). Other
237 -- attributes (font face, slant, weight; fill color, stroke color,
238 -- opacity) must be accumulated.
239 cairoStyle :: Style v Double -> RenderM ()
240 cairoStyle s =
241 sequence_
242 . catMaybes $ [ handle clip
243 , handle lFillRule
244 , handle lWidth
245 , handle lCap
246 , handle lJoin
247 , handle lDashing
248 ]
249 where handle :: AttributeClass a => (a -> RenderM ()) -> Maybe (RenderM ())
250 handle f = f `fmap` getAttr s
251 clip = mapM_ (\p -> cairoPath p >> liftC C.clip) . op Clip
252 lFillRule = liftC . C.setFillRule . fromFillRule . getFillRule
253 lWidth = liftC . C.setLineWidth . getLineWidth
254 lCap = liftC . C.setLineCap . fromLineCap . getLineCap
255 lJoin = liftC . C.setLineJoin . fromLineJoin . getLineJoin
256 lDashing (getDashing -> Dashing ds offs) =
257 liftC $ C.setDash ds offs
258
259 fromFontSlant :: FontSlant -> P.FontStyle
260 fromFontSlant FontSlantNormal = P.StyleNormal
261 fromFontSlant FontSlantItalic = P.StyleItalic
262 fromFontSlant FontSlantOblique = P.StyleOblique
263
264 fromFontWeight :: FontWeight -> P.Weight
265 fromFontWeight FontWeightBold = P.WeightBold
266 fromFontWeight _ = P.WeightNormal
267
268 -- | Multiply the current transformation matrix by the given 2D
269 -- transformation.
270 cairoTransf :: T2 Double -> C.Render ()
271 cairoTransf t = C.transform m
272 where m = CM.Matrix a1 a2 b1 b2 c1 c2
273 (unr2 -> (a1,a2)) = apply t unitX
274 (unr2 -> (b1,b2)) = apply t unitY
275 (unr2 -> (c1,c2)) = transl t
276
277 fromLineCap :: LineCap -> C.LineCap
278 fromLineCap LineCapButt = C.LineCapButt
279 fromLineCap LineCapRound = C.LineCapRound
280 fromLineCap LineCapSquare = C.LineCapSquare
281
282 fromLineJoin :: LineJoin -> C.LineJoin
283 fromLineJoin LineJoinMiter = C.LineJoinMiter
284 fromLineJoin LineJoinRound = C.LineJoinRound
285 fromLineJoin LineJoinBevel = C.LineJoinBevel
286
287 fromFillRule :: FillRule -> C.FillRule
288 fromFillRule Winding = C.FillRuleWinding
289 fromFillRule EvenOdd = C.FillRuleEvenOdd
290
291 instance Renderable (Segment Closed V2 Double) Cairo where
292 render _ (Linear (OffsetClosed v)) = C . liftC $ uncurry C.relLineTo (unr2 v)
293 render _ (Cubic (unr2 -> (x1,y1))
294 (unr2 -> (x2,y2))
295 (OffsetClosed (unr2 -> (x3,y3))))
296 = C . liftC $ C.relCurveTo x1 y1 x2 y2 x3 y3
297
298 instance Renderable (Trail V2 Double) Cairo where
299 render _ = withTrail renderLine renderLoop
300 where
301 renderLine ln = C $ do
302 mapM_ renderC (lineSegments ln)
303
304 -- remember that we saw a Line, so we will ignore fill attribute
305 ignoreFill .= True
306
307 renderLoop lp = C $ do
308 case loopSegments lp of
309 -- let closePath handle the last segment if it is linear
310 (segs, Linear _) -> mapM_ renderC segs
311
312 -- otherwise we have to draw it explicitly
313 _ -> mapM_ renderC (lineSegments . cutLoop $ lp)
314
315 liftC C.closePath
316
317 instance Renderable (Path V2 Double) Cairo where
318 render _ p = C $ do
319 cairoPath p
320 f <- getStyleAttrib getFillTexture
321 s <- getStyleAttrib getLineTexture
322 ign <- use ignoreFill
323 setTexture f
324 when (isJust f && not ign) $ liftC C.fillPreserve
325 setTexture s
326 liftC C.stroke
327
328 -- Add a path to the Cairo context, without stroking or filling it.
329 cairoPath :: Path V2 Double -> RenderM ()
330 cairoPath (Path trs) = do
331 liftC C.newPath
332 ignoreFill .= False
333 F.mapM_ renderTrail trs
334 where
335 renderTrail (viewLoc -> (unp2 -> p, tr)) = do
336 liftC $ uncurry C.moveTo p
337 renderC tr
338
339 addStop :: MonadIO m => C.Pattern -> GradientStop Double -> m ()
340 addStop p s = C.patternAddColorStopRGBA p (s^.stopFraction) r g b a
341 where
342 (r,g,b,a) = colorToSRGBA (s^.stopColor)
343
344 cairoSpreadMethod :: SpreadMethod -> C.Extend
345 cairoSpreadMethod GradPad = C.ExtendPad
346 cairoSpreadMethod GradReflect = C.ExtendReflect
347 cairoSpreadMethod GradRepeat = C.ExtendRepeat
348
349 -- XXX should handle opacity in a more straightforward way, using
350 -- cairo's built-in support for transparency? See also
351 -- https://github.com/diagrams/diagrams-cairo/issues/15 .
352 setTexture :: Maybe (Texture Double) -> RenderM ()
353 setTexture Nothing = return ()
354 setTexture (Just (SC (SomeColor c))) = do
355 o <- fromMaybe 1 <$> getStyleAttrib getOpacity
356 liftC (C.setSourceRGBA r g b (o*a))
357 where (r,g,b,a) = colorToSRGBA c
358 setTexture (Just (LG g)) = liftC $
359 C.withLinearPattern x0 y0 x1 y1 $ \pat -> do
360 mapM_ (addStop pat) (g^.lGradStops)
361 C.patternSetMatrix pat m
362 C.patternSetExtend pat (cairoSpreadMethod (g^.lGradSpreadMethod))
363 C.setSource pat
364 where
365 m = CM.Matrix a1 a2 b1 b2 c1 c2
366 [[a1, a2], [b1, b2], [c1, c2]] = matrixHomRep (inv (g^.lGradTrans))
367 (x0, y0) = unp2 (g^.lGradStart)
368 (x1, y1) = unp2 (g^.lGradEnd)
369 setTexture (Just (RG g)) = liftC $
370 C.withRadialPattern x0 y0 r0 x1 y1 r1 $ \pat -> do
371 mapM_ (addStop pat) (g^.rGradStops)
372 C.patternSetMatrix pat m
373 C.patternSetExtend pat (cairoSpreadMethod (g^.rGradSpreadMethod))
374 C.setSource pat
375 where
376 m = CM.Matrix a1 a2 b1 b2 c1 c2
377 [[a1, a2], [b1, b2], [c1, c2]] = matrixHomRep (inv (g^.rGradTrans))
378 (r0, r1) = (g^.rGradRadius0, g^.rGradRadius1)
379 (x0', y0') = unp2 (g^.rGradCenter0)
380 (x1', y1') = unp2 (g^.rGradCenter1)
381 (x0, y0, x1, y1) = (x0' * (r1 - r0) / r1, y0' * (r1 - r0) / r1, x1' ,y1')
382
383 -- Can only do PNG files at the moment...
384 instance Renderable (DImage Double External) Cairo where
385 render _ (DImage path w h tr) = C . liftC $ do
386 let ImageRef file = path
387 if ".png" `isSuffixOf` file
388 then do
389 C.save
390 cairoTransf (tr <> reflectionY)
391 pngSurfChk <- liftIO (try $ C.imageSurfaceCreateFromPNG file
392 :: IO (Either IOError C.Surface))
393 case pngSurfChk of
394 Right pngSurf -> do
395 w' <- C.imageSurfaceGetWidth pngSurf
396 h' <- C.imageSurfaceGetHeight pngSurf
397 let sz = fromIntegral <$> dims2D w h
398 cairoTransf $ requiredScaling sz (fromIntegral <$> V2 w' h')
399 C.setSourceSurface pngSurf (-fromIntegral w' / 2)
400 (-fromIntegral h' / 2)
401 Left _ ->
402 liftIO . putStrLn $
403 "Warning: can't read image file <" ++ file ++ ">"
404 C.paint
405 C.restore
406 else
407 liftIO . putStr . unlines $
408 [ "Warning: Cairo backend can currently only render embedded"
409 , " images in .png format. Ignoring <" ++ file ++ ">."
410 ]
411
412 -- Copied from Rasterific backend. This function should probably be in JuicyPixels!
413 toImageRGBA8 :: DynamicImage -> Image PixelRGBA8
414 toImageRGBA8 (ImageRGBA8 i) = i
415 toImageRGBA8 (ImageRGB8 i) = promoteImage i
416 toImageRGBA8 (ImageYCbCr8 i) = promoteImage (convertImage i :: Image PixelRGB8)
417 toImageRGBA8 (ImageY8 i) = promoteImage i
418 toImageRGBA8 (ImageYA8 i) = promoteImage i
419 toImageRGBA8 (ImageCMYK8 i) = promoteImage (convertImage i :: Image PixelRGB8)
420 toImageRGBA8 _ = error "Unsupported Pixel type"
421
422 instance Renderable (DImage Double Embedded) Cairo where
423 -- render _ (DImage path w h tr) =
424 render _ (DImage iD _w _h tr) = C . liftC $ do
425 C.save
426 cairoTransf (tr <> reflectionY)
427
428 let fmt = C.FormatARGB32
429 dataSurf <- liftIO $ C.createImageSurface fmt w h
430
431 surData :: C.SurfaceData Int Word32
432 <- liftIO $ C.imageSurfaceGetPixels dataSurf
433
434 stride <- C.imageSurfaceGetStride dataSurf
435
436 _ <- forMOf imageIPixels img $ \(x, y, px) -> do
437 let p = y * (stride`div`4) + x
438 liftIO . MA.writeArray surData p $ toARGB px
439 return px
440
441 C.surfaceMarkDirty dataSurf
442
443 w' <- C.imageSurfaceGetWidth dataSurf
444 h' <- C.imageSurfaceGetHeight dataSurf
445 let sz = fromIntegral <$> dims2D w h
446 cairoTransf $ requiredScaling sz (fromIntegral <$> V2 w' h')
447 C.setSourceSurface dataSurf (-fromIntegral w' / 2)
448 (-fromIntegral h' / 2)
449
450 C.paint
451 C.restore
452 where
453 ImageRaster dImg = iD
454 img@(Image w h _) = toImageRGBA8 dImg
455
456
457 {-# INLINE toARGB #-}
458 -- Actually the name should be toBGRA, since that's the component order used by Cairo.
459 -- Really, what's happening here is just a swap of the R and B channels.
460 -- It seems a lot like this is dependent on endianness; perhaps we should handle this...
461 toARGB :: PixelRGBA8 -> Word32
462 toARGB px = ga + rotateL rb 16
463 where rgba = packPixel px
464 rb = rgba .&. 0x00FF00FF
465 ga = rgba .&. 0xFF00FF00
466
467 if' :: Monad m => (a -> m ()) -> Maybe a -> m ()
468 if' = maybe (return ())
469
470 instance Renderable (Text Double) Cairo where
471 render _ txt = C $ do
472 save
473 setTexture =<< getStyleAttrib getFillTexture
474 sty <- use accumStyle
475 layout <- liftC $ layoutStyledText sty txt
476 -- Uncomment the lines below to draw a rectangle at the extent of each Text
477 -- let (w, h) = unr2 $ ref ^* 2 -- XXX Debugging
478 -- cairoPath $ rect w h -- XXX Debugging
479 liftC $ do
480 -- C.setLineWidth 0.5 -- XXX Debugging
481 -- C.stroke -- XXX Debugging
482 -- C.newPath -- XXX Debugging
483 P.showLayout layout
484 C.newPath
485 restore
486
487 layoutStyledText :: Style V2 Double -> Text Double -> C.Render P.PangoLayout
488 layoutStyledText sty (Text tt al str) =
489 let tr = tt <> reflectionY
490 styAttr :: AttributeClass a => (a -> b) -> Maybe b
491 styAttr f = fmap f $ getAttr sty
492 ff = styAttr getFont
493 fs = styAttr fromFontSlant
494 fw = styAttr fromFontWeight
495 size' = styAttr getFontSize
496 in do
497 cairoTransf tr -- non-uniform scale
498 layout <- P.createLayout str
499 -- set font, including size
500 liftIO $ do
501 font <- P.fontDescriptionNew
502 if' (P.fontDescriptionSetFamily font) ff
503 if' (P.fontDescriptionSetStyle font) fs
504 if' (P.fontDescriptionSetWeight font) fw
505 if' (P.fontDescriptionSetSize font) size'
506 P.layoutSetFontDescription layout $ Just font
507 -- geometric translation
508 ref <- liftIO $ case al of
509 BoxAlignedText xt yt -> do
510 (_,P.PangoRectangle _ _ w h) <- P.layoutGetExtents layout
511 return $ r2 (w * xt, h * (1 - yt))
512 BaselineText -> do
513 baseline <- P.layoutIterGetBaseline =<< P.layoutGetIter layout
514 return $ r2 (0, baseline)
515 let t = moveOriginBy ref mempty :: T2 Double
516 cairoTransf t
517 P.updateLayout layout
518 return layout