Permalink
Browse files

Add module Diagrams.Backend.Cairo.Ptr

Used for rendering to buffers in memory.
  • Loading branch information...
1 parent 5f0cf2f commit 5d36746f3b49b3a7c3c8437cc6abd98bc5206421 @haasn haasn committed Nov 18, 2012
Showing with 42 additions and 0 deletions.
  1. +1 −0 diagrams-cairo.cabal
  2. +41 −0 src/Diagrams/Backend/Cairo/Ptr.hs
View
@@ -37,6 +37,7 @@ Library
Exposed-modules: Diagrams.Backend.Cairo
Diagrams.Backend.Cairo.CmdLine
Diagrams.Backend.Cairo.Internal
+ Diagrams.Backend.Cairo.Ptr
Diagrams.Backend.Cairo.Text
Hs-source-dirs: src
Build-depends: base >= 4.2 && < 4.7,
@@ -0,0 +1,41 @@
+module Diagrams.Backend.Cairo.Ptr where
+
+import Data.Word (Word8)
+
+import Diagrams.Prelude (Diagram, R2, SizeSpec2D (..), renderDia)
+import Diagrams.Backend.Cairo
+import Diagrams.Backend.Cairo.Internal
+
+import Foreign.ForeignPtr.Safe (ForeignPtr, newForeignPtr)
+import Foreign.Marshal.Alloc (finalizerFree)
+import Foreign.Marshal.Array (mallocArray)
+import Foreign.Ptr (Ptr, castPtr)
+
+import Graphics.Rendering.Cairo ( Format (..)
+ , formatStrideForWidth
+ , renderWith
+ , withImageSurfaceForData
+ )
+
+-- | Render a diagram to a new buffer in memory, with the format ARGB32.
+
+renderPtr :: Int -> Int -> Diagram Cairo R2 -> IO (Ptr Word8)
+renderPtr w h d = do
+ let stride = formatStrideForWidth FormatARGB32 w
+ size = stride * h
+ opt = CairoOptions
+ { cairoSizeSpec = Dims (fromIntegral w) (fromIntegral h)
+ , cairoOutputType = RenderOnly
+ , cairoBypassAdjust = False
+ , cairoFileName = ""
+ }
+ (_, r) = renderDia Cairo opt d
+
+ b <- mallocArray size
+ withImageSurfaceForData b FormatARGB32 w h stride (`renderWith` r)
+ return (castPtr b)
+
+-- | Like 'renderPtr' but automatically garbage collected by Haskell.
+
+renderForeignPtr :: Int -> Int -> Diagram Cairo R2 -> IO (ForeignPtr Word8)
+renderForeignPtr w h d = renderPtr w h d >>= newForeignPtr finalizerFree

0 comments on commit 5d36746

Please sign in to comment.