Debian Codegraph @

src/Diagrams/Backend/Cairo/List.hs

raw
1 {-# LANGUAGE CPP #-}
2 -----------------------------------------------------------------------------
3 -- |
4 -- Module : Diagrams.Backend.Cairo.List
5 -- Copyright : (c) 2012 Diagrams-cairo team (see LICENSE)
6 -- License : BSD-style (see LICENSE)
7 -- Maintainer : [email protected]
8 --
9 -- Render a diagram directly to a list of lists of Colour values
10 -- (/i.e./ pixels).
11 --
12 -----------------------------------------------------------------------------
13
14 module Diagrams.Backend.Cairo.List where
15
16 #if __GLASGOW_HASKELL__ < 710
17 import Control.Applicative ((<$>))
18 #endif
19
20 import Control.Exception (bracket)
21
22 import Data.Colour
23 import Data.Colour.SRGB (sRGB)
24 import Data.Word (Word8)
25
26 import Diagrams.Backend.Cairo (Cairo)
27 import Diagrams.Backend.Cairo.Ptr (renderPtr)
28 import Diagrams.Prelude (Any, QDiagram, V2)
29 import Graphics.Rendering.Cairo (Format (..))
30
31 import Foreign.Marshal.Alloc (free)
32 import Foreign.Marshal.Array (peekArray)
33
34 -- | Render to a regular list of Colour values.
35
36 renderToList :: (Ord a, Floating a) =>
37 Int -> Int -> QDiagram Cairo V2 Double Any -> IO [[AlphaColour a]]
38 renderToList w h d =
39 f 0 <$> bracket (renderPtr w h FormatARGB32 d) free (peekArray $ w*h*4)
40 where
41 f :: (Ord a, Floating a) => Int -> [Word8] -> [[AlphaColour a]]
42 f _ [] = []
43 f n xs | n >= w = [] : f 0 xs
44 f n (g:b:r:a:xs) =
45 let l x = fromIntegral x / fromIntegral a
46 c = sRGB (l r) (l g) (l b) `withOpacity` (fromIntegral a / 255)
47
48 in case f (n+1) xs of
49 [] -> [[c]]
50 cs:ys -> (c:cs) : ys
51
52 f _ _ = error "renderToList: Internal format error"