{- Hey Emacs, this is -*- haskell -*- !
HOpenGL - a binding of OpenGL and GLUT for Haskell.
Copyright (c) 2002, Sven Panne
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

3. Neither the name of the author nor the names of its contributors may be
   used to endorse or promote products derived from this software without
   specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-}

module GL_Marshal (
   module Foreign,

   marshal,           -- ::  Storable a        =>       a  -> IO Addr
   marshalList,       -- ::  Storable a        =>      [a] -> IO (Int, Addr),
   marshalListZero,   -- ::  Storable a        => a -> [a] -> IO Addr

   unmarshal,         -- ::  Storable a        =>        Addr -> IO  a
   unmarshalList,     -- ::  Storable a        => Int -> Addr -> IO [a]
   unmarshalListZero, -- :: (Storable a, Eq a) => a   -> Addr -> IO [a]

   inParamWith,       -- :: (a -> IO c) ->                   (c -> Addr) -> (c    -> IO b) -> a -> IO  b
   inParam,           -- :: Storable a =>                                   (Addr -> IO b) -> a -> IO  b
   inOutParamWith,    -- :: (a -> IO c) -> (c    -> IO a) -> (c -> Addr) -> (c    -> IO b) -> a -> IO (b,a)
   inOutParam,        -- :: Storable a =>                                   (Addr -> IO b) -> a -> IO (b,a)
   outParamWith,      -- :: (a -> Int) ->  (Addr -> IO a) ->                (Addr -> IO b)      -> IO (b,a)
   outParam,          -- :: Storable a =>                                   (Addr -> IO b)      -> IO (b,a)

   Marshal,
   runMarshal,        -- :: Marshal a -> Addr -> IO (a, Addr)
   getAddr,           -- :: Marshal Addr
   incAddr,           -- :: Int -> Marshal ()
   iOToMarshal,       -- :: IO a -> Marshal a

   peekM,             -- :: Storable a =>      Marshal a
   peekAlignedM,      -- :: Storable a =>      Marshal a
   pokeM,             -- :: Storable a => a -> Marshal ()
   pokeAlignedM,      -- :: Storable a => a -> Marshal ()

   module CString
) where

import Foreign
import CString(CString, newCString, peekCString, withCString)

----------------------------------------------------------------------
-- convenience functions for (un-)marshaling

-- Performance paranoia, one could use:
-- marshal x = marshalList [x]
marshal :: Storable a => a -> IO (Ptr a)
marshal = new

marshalList :: Storable a => [a] -> IO (Int, Ptr a)
marshalList vals = do ptr <- newArray vals ; return (length vals, ptr)

-- Performance paranoia, one could use:
-- marshalListZero zeroElem xs = marshalList (xs ++ [zeroElem])
marshalListZero :: Storable a => a -> [a] -> IO (Ptr a)
marshalListZero = newArray0

-- Performance paranoia, one could use:
-- unmarshal buf = liftM head $ unmarshalList 1 buf
unmarshal ::  Storable a => Ptr a -> IO a
unmarshal = peek

unmarshalList :: Storable a => Int -> Ptr a -> IO [a]
unmarshalList = peekArray

unmarshalListZero :: (Storable a, Eq a) => a -> Ptr a -> IO [a]
unmarshalListZero = peekArray0

----------------------------------------------------------------------

inParamWith :: (a -> IO c) -> (c -> Ptr d) -> (c -> IO b) -> a -> IO b
inParamWith marshal_ selAddr act x = do
   marshRes <- marshal_ x
   val <- act marshRes
   free (selAddr marshRes)
   return val

inParam :: Storable a => (Ptr a -> IO b) -> a -> IO b
inParam = flip withObject

inOutParamWith :: (a -> IO c) -> (c -> IO a) -> (c -> Ptr d) -> (c -> IO b) -> a -> IO (b,a)
inOutParamWith marshal_ unmarshal_ sel act x = do
   marshRes <- marshal_ x
   retVal <- act marshRes
   val <- unmarshal_ marshRes
   free (sel marshRes)
   return (retVal, val)

inOutParam :: Storable a => (Ptr a -> IO b) -> a -> IO (b,a)
inOutParam act x =
   withObject x $ \ptr -> do
   b <- act ptr
   a <- peek ptr
   return (b,a)

outParamWith :: (a -> Int) -> (Ptr c -> IO a) -> (Ptr c -> IO b) -> IO (b,a)
outParamWith sizeOf_ unmarshal_ act = do
   buf <- mallocBytes (sizeOf_ undefined)
   retVal <- act buf
   val <- unmarshal_ buf
   free buf
   return (retVal, val)

outParam :: Storable a => (Ptr a -> IO b) -> IO (b,a)
outParam act =
   alloca $ \ptr -> do
   b <- act ptr
   a <- peek ptr
   return (b,a)

----------------------------------------------------------------------
-- A simple state monad, keeping track of the current buffer addr.

newtype Marshal a = Marshal { runMarshal :: Ptr () -> IO (a, Ptr ()) }

instance Functor Marshal where
   fmap f p = Marshal (\a -> do (x, a') <- runMarshal p a
                                return (f x, a'))

instance Monad Marshal where
   return v = Marshal (\a -> return (v, a))
   p >>= f  = Marshal (\a -> do (x, a') <- runMarshal p a
                                runMarshal (f x) a')

getAddr :: Marshal (Ptr a)
getAddr = Marshal (\a -> return (castPtr a, a))

-- only used internally
putAddr :: Ptr a -> Marshal ()
putAddr a = Marshal (\_ -> return ((), castPtr a))

incAddr :: Int -> Marshal ()
incAddr i = do
   a <- getAddr
   putAddr (a `plusPtr` i)

-- monad transformer
iOToMarshal :: IO a -> Marshal a
iOToMarshal f = Marshal (\a -> do x <- f
                                  runMarshal (return x) a)
-- only used internally
alignAddrM :: Storable a => a -> Marshal ()
alignAddrM x = do
   addr <- getAddr
   putAddr (alignPtr addr (alignment x))

peekM :: Storable a => Marshal a
peekM = do
   a <- getAddr
   x <- iOToMarshal $ peek a
   incAddr (sizeOf x)
   return x

peekAlignedM :: Storable a => Marshal a
peekAlignedM = pa alignAddrM
   where pa :: Storable b => (b -> Marshal ()) -> Marshal b
         pa align = do align undefined
                       peekM

pokeM :: Storable a => a -> Marshal ()
pokeM x = do
   a <- getAddr
   iOToMarshal $ poke a x
   incAddr (sizeOf x)

pokeAlignedM :: Storable a => a -> Marshal ()
pokeAlignedM x = do
   alignAddrM x
   pokeM x
